需要帮助的Java循环混淆
所以我需要帮助,我试图输入一个Y/N程序,但它不接受一个大的“Y”或“N”。另外一件我正在尝试做的事情是,在按下'Y'/'Y'之后,我试图让程序返回到上面编写的代码。示例显示“123”的程序,是否需要继续?是/否,如果输入是,则返回以从头开始重新启动程序。请帮帮我需要帮助的Java循环混淆,java,Java,所以我需要帮助,我试图输入一个Y/N程序,但它不接受一个大的“Y”或“N”。另外一件我正在尝试做的事情是,在按下'Y'/'Y'之后,我试图让程序返回到上面编写的代码。示例显示“123”的程序,是否需要继续?是/否,如果输入是,则返回以从头开始重新启动程序。请帮帮我 System.out.println("continue? Yes or no "); char check = s.next().charAt(0); while (check != 'y' &&
System.out.println("continue? Yes or no ");
char check = s.next().charAt(0);
while (check != 'y' && response != 'n')// corrected this part, however need help with restarting the loop back to the first line of code in a loop {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
} if ((check == 'n') || (check == 'N')) {
// I tried (check == 'n' || check == 'N')
System.out.println("Program terminated goodbye.");
System.exit(0);
} else if (check == 'y') {
//need help with restarting the loop back to the first line of code in a loop
}
我想这就是你要找的
char check;
Scanner scanner = new Scanner(System.in);
do
{
//your piece of code in here e.g.
System.out.println("Printed 123");
System.out.println("Do you wish to continue?[Y/y] or [N/n]");
choice = scanner.next().charAt(0);
}while (check =='Y' || check == 'y');
System.out.println("Program terminated goodbye.");
检查条件之前,
do while
循环至少运行一次,因此当用户输入Y或Y时,条件将为true,这意味着他们希望循环再次运行。如果用户输入任何其他值,则条件将变为false,因为选择既不是Y也不是Y,循环将终止。如果要在不区分大小写的情况下进行检查,则应将字符转换为字符串,然后执行s1.equalsIgnoreCase(s2)代码>
所以
为了回到第一行,我使用了一个while循环,它将永远循环
最后,如果是n,则退出,否则返回循环的第一行。使用String.equals()比较字符串的值,==比较内存中的字符串。请正确格式化您的代码。我不知道我哪里出错了,因此出现了这个问题。您编写的代码不接受任何大写输入,那你为什么希望它接受呢?天哪,你是对的。。。我真傻。。我纠正了那部分。在按下y键后,你知道如何继续该程序返回顶部吗?该部分已经回答了一些问题。搜索Stackoverflow,你会找到它们。char
和String
是非常不同的char
是一个原语,它没有任何方法。(实际上它是一个整数类型,像int
,当然可以与==
)我的错,我认为它是一个字符串。看看我在Simone的回答中已经评论过的编辑,代码比较的是char
而不是String
,而char
比较的是=
,因为它是一个原语(在Java中)
while(true) {
System.out.println("Continue? [Y/N]");
char check_char = s.next().charAt(0);
String check = Character.toString(check_char);
while(check.equalsIgnoreCase("y") && !response.equalsIgnoreCase("n")) {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
}
if (check.equalsIgnoreCase("n")) {
System.out.println("Program terminated goodbye.");
System.exit(0);
}
}