gpt4 book ai didi

java - 循环切换以打印输出值

转载 作者:行者123 更新时间:2023-12-01 11:37:12 26 4
gpt4 key购买 nike

我正在循环中处理 Switch 语句。我想添加名称并为这些名称分配字母,然后根据字母打印出总值。问题是它不会读取字母的指定值,正如您在下面的代码中看到的那样。例如,对于 Mike,我分配了 A,A 的值为 10。对于 Joe,我分配了 B,B 的值为 7。所以我需要 A+B 的总值乘以固定值 3,即是 51。我肯定做错了什么,想知道是否可以在不使用对象和其他方法的情况下做到这一点。

import java.util.Scanner;
public class TotalScore {

public static void main(String[] args) {
double lettervalue = 0,fixedvalue=3,totalvalue;
int count,repeatcount;
String valuename = "";
String letter="";


Scanner input = new Scanner(System.in);
System.out.print("How many values do you want to process? ");
count=input.nextInt();
input.nextLine();

for(repeatcount=0;repeatcount<count;++repeatcount){

System.out.print("Enter name for value " +(repeatcount+1)+" ");
valuename = valuename+input.nextLine()+"\n";
System.out.print("Enter letter A,B,C or D for named value ");
letter = letter+input.nextLine()+"\n";


switch(letter){
case "A":case"a": lettervalue=10.0;
break;
case "B":case"b": lettervalue=7.0;
break;

case "C":case"c": lettervalue=5.0;
break;
case "D":case"d": lettervalue=2.0;
break;
default: lettervalue=0;



}

}
totalvalue=lettervalue*fixedvalue;
System.out.println("The value names are\n "+valuename);
System.out.println("The letter values you entered are\n "+letter);
System.out.println("The total value is "+totalvalue);



}

}

Output:
How many values do you want to process? 2
Enter name for value 1 Mike
Enter letter A,B,C or D for named value A
Enter name for value 2 Joe
Enter letter A,B,C or D for named value B
The value names are
Mike
Joe

The letter values you entered are
A
B

The total value is 0.0

最佳答案

letter 应仅包含您的输入值。然后你可以有一个单独的字符串来跟踪你的总输入。

String inputs = "";
String letter = "";

/*for loop etc.*/
letter = input.nextLine();

/*switch statement*/

inputs += valuename + letter + lettervalue + "\n"; //String.valueOf() is not necessary
totalvalue += lettervalue * fixedvalue;

/*end loop*/

System.out.println(inputs);

关于java - 循环切换以打印输出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29856959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com