英文:
How can I terminate a do-while loop after execution?
问题
我不确定在这段代码中哪个语句应该用(choice!=o);
来替换:
choice
是一个 char 类型,用于 switch case 语句中的 Y、y、N、n。- 在
checkEmployment()
和evaluate()
运行结束后终止,或者在调用default
后终止。
do {
System.out.println("你是否就业?");
System.out.println("[Y] 我已就业。");
System.out.println("[N] 我未就业。");
choice = inputInfo.next().charAt(0);
switch(choice) {
case 'Y': checkEmployment();
break;
case 'y': checkEmployment();
break;
case 'N': evaluate();
break;
case 'n': evaluate();
break;
default: System.out.println("无效的输入。程序终止。");
break;
} // 这是就业状态的条件语句。
} while(choice != 'o'); // 这是就业状态的 do-while 循环语句。
我正在学习,任何帮助都将不胜感激。干杯。
英文:
I’m not sure what statement should be replaced with (choice!=o);
in this code:
choice
is a char for the switch case Y,y,N,n.- Terminate after
checkEmployment()
andevaluate()
is finished running, or ifdefault
is invoked
do {
System.out.println("Are you employed?");
System.out.println("[Y] I am employed.");
System.out.println("[N] I am unemployed.");
choice = inputInfo.next().charAt(0);
switch(choice) {
case 'Y': checkEmployment();
break;
case 'y': checkEmployment();
break;
case 'N': evaluate();
break;
case 'n': evaluate();
break;
default: System.out.println("Invalid input. Terminating Program");
break;
}//This is the conditional for the employment status.
} while(choice!='o'); //This is the do-while statement for the employment status.
I’m learning and any help would be appreciated. Cheers.
答案1
得分: 1
你可以通过移除两个break语句来简化switch语句。然后,我会添加一个布尔变量来跟踪有效输入。将其用作while循环的条件。
boolean validInput = false;
do {
System.out.println("你是否就业?");
System.out.println("[Y] 我已就业。");
System.out.println("[N] 我未就业。");
choice = inputInfo.next().charAt(0);
switch(choice) {
case 'Y':
case 'y':
validInput = true;
checkEmployment();
break;
case 'N':
case 'n':
validInput = true;
evaluate();
break;
default:
System.out.println("错误 - 无效输入");
break;
}
} while (!validInput);
英文:
You can tidy the switch statement up a bit by getting rid of two of the breaks. Then I would add a boolean to keep track of valid input. Use that as your while condition.
boolean validInput = false;
do {
System.out.println("Are you employed?");
System.out.println("[Y] I am employed.");
System.out.println("[N] I am unemployed.");
choice = inputInfo.next().charAt(0);
switch(choice) {
case 'Y':
case 'y':
validInput = true;
checkEmployment();
break;
case 'N':
case 'n':
validInput = true;
evaluate();
break;
default:
System.out.println("Error - invalid input");
break;
}
} while (!validInput);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论