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' && 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 时,条件将为真,这意味着他们希望循环再次运行。如果用户输入任何其他值,则条件将变为假,因为选择既不是 Y 也不是 y 并且循环将终止。
推荐阅读
- python - 有没有人在使用 webbot 时遇到过这个错误
- redux - Redux Saga socket.io
- c# - 无法测试回文
- javascript - Firebase 制定安全规则以仅允许获取查询大小
- php - CURL PHP试图获取非对象的属性
- reactjs - 切换具有状态依赖的组件
- css - 使用grid而不是flex在最后一行排列一些项目
- javascript - 如何将登录的用户 ID 传递给 Bigcommerce 中的 iframe url
- asp.net-mvc - 如何检查一组值在实体框架中的某个日期/工作日下出现了多少次
- amazon-web-services - 使用 Cognito 防止多个同时登录