gpt4 book ai didi

java - 案例 Q 无法解析为变量

转载 作者:行者123 更新时间:2023-11-29 04:54:10 25 4
gpt4 key购买 nike

使用case编写程序,case为12Q

案例 12 工作正常,但用于退出程序的案例 Q 无法解析为变量( Q 无法解析为变量)

要遵循的代码片段:

        System.out.print("-- MENU -- \n");
System.out.print("1: Display Journeys \n");
System.out.print("2: Identify Suitable Journeys \n");
System.out.print("Q: Quit \n");
System.out.print("Pick an option: ");

int option = console.nextInt();

switch(option) {
case 1:
while(INPUT.hasNextLine()) {
System.out.println(INPUT.nextLine());
}
break;

case 2:

System.out.print("Specify desired location: ");
String destination = console.next();

System.out.print("Specify Max Time (HH:MM): ");
String choice = console.next();

// save the index of the colon
int colon = choice.indexOf(':');

// strip the hours preceding the colon then convert to int
int givenHours = Integer.parseInt(choice.substring(0, colon));
// strip the mins following the colon then convert to int
int givenMins = Integer.parseInt(choice.substring(colon + 1, choice.length()));

// calculate the time's total mins
int maxMins = (givenHours * 60) + givenMins;

System.out.print("Specify maximum changes: ");
int maxChange = console.nextInt();

// gui spacing
System.out.println();

// skips the first line which is York
INPUT.nextLine();
int mins = INPUT.nextInt();
int change = INPUT.nextInt();

if ((mins > maxMins) || ((change > maxChange)) && (destination.equals("York") || destination.equals("Alnwick"))) {
System.out.format("Time: %02d:%02d, Changes: %d = Unsuitable \n", (mins / 60), (mins % 60), change);
}
else {
System.out.format("Time: %02d:%02d, Changes: %d = Suitable \n", (mins / 60), (mins % 60), change);
}
//Do stuff
break;

case Q:

System.exit(0);

最佳答案

问题是您在 int 上使用 switch 表达式,因此 1 和 2 是有效值,但不带引号的 Q 是一个变量名,它在您的程序中不存在。

您可能指的是“Q”或“q”,它们都不起作用 - 因为它不是整数。

如果您的可选值是 1,2 和 Q,您应该使用字符串,在您的情况下使用“1”、“2”和“Q”

这也需要改变:

int option = console.nextInt();

到:

String option = console.nextString();

关于java - 案例 Q 无法解析为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34363677/

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