如何在用户要求时显示变量?

时间:2015-01-15 14:59:13

标签: java user-input

基本上,我希望用户输入'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);

3 个答案:

答案 0 :(得分:1)

您可以使用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);
}

答案 1 :(得分:0)

您可以使用扫描仪:

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

答案 2 :(得分:0)

使用扫描仪。根据输入,显示所需的输出。此外,变量应该是lowerCamelCase以符合Java coding standards

这会检查以确保在显示结果之前输入有效输入。

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'.");
    }
}