java—当用户请求变量时,如何显示它?

0vvn1miw  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(266)

基本上,我希望用户输入'average'或'sum',这样我就可以显示使用system.out.println()请求的相关值;
但我该怎么做呢(抱歉,如果这真的很简单)

int SumChocolates = 0;
SumChocolates = (int) (data [0][7] + data [1][7] + data [2][7] + data [3][7]);

int AvgChocolates = 0;
AvgChocolates = (int) (SumChocolates / 4);
cyvaqqii

cyvaqqii1#

你可以使用 Scanner 然后使用 Scanner.nextLine(); 从控制台中的用户获取输入。
另外,您可能想看看java中的标准命名模式

Scanner scan = new Scanner(System. in ); //Create a new Scanner
System.out.println("Would you like the average, or sum?");
String input = scan.nextLine(); //Get input from the user

int SumChocolates = 0; //Must declare out here, because Average case uses this
SumChocolates = (int)(data[0][7] + data[1][7] + data[2][7] + data[3][7]);

if (input.equalsIgnoreCase("Sum")) {
    System.out.println("The Sum is: " + SumChocolates);
} else if (input.equalsIgnoreCase("Average")) {
    int AvgChocolates = 0;
    AvgChocolates = (int)(SumChocolates / 4);
    System.out.println("The average is: " + AvgChocolates);
}
cbjzeqam

cbjzeqam2#

使用扫描仪。根据它们的输入,显示所需的输出。此外,变量应该是较低的,以符合java编码标准。
这将检查以确保在显示结果之前输入有效的输入。

Scanner s = new Scanner(System.in);
String input = "";
System.out.println("Would you like to see the Average, or the Sum?");

while (true) {
    input = s.nextLine();
    if (input.equalsIgnoreCase("Average")) {
        System.out.println(avgChocolates);
        break;
    } else if (input.equalsIgnoreCase("Sum")) {
        System.out.println(sumChocolates);
        break;
    } else {
        System.out.println("Invalid input. Please enter 'Average' or 'Sum'.");
    }
}
igsr9ssn

igsr9ssn3#

您可以使用扫描仪:

Scanner scanner = new Scanner(System.in);
String userInput = scanner.next();

相关问题