我正在寻找一种仅允许答案 1 或 2 的解决方案。如果输入了另一个答案,如何再次请求输入?谢谢!
System.out.println("Are you single or married? \n 1 - Single \n 2 - Married");
status = in.nextInt(); //allow input for status
do{
System.out.println("Are you single or married? \n 1 - Single \n 2 - Married");
status = in.nextInt(); //allow input for status
}while((status!=1)&&(status!=2));
这将继续打印相同的问题,直到答案为 1 或 2。System.out.print("\f");
出于审美目的,您可能希望在提出问题之前添加一个以清除屏幕。
这是一种简单的方法,但我建议您自己进行一些研究,因为我相信您可以想出一个更符合您喜好的答案:
boolean right=false;
do{
System.out.println("Are you single or married? \n 1 - Single \n 2 - Married");
status = in.nextInt();
if(status.equals("1") || status.equals("2");{right=true;}
}
while(status==false);
我建议研究while
循环和if-statements
:
希望这可以帮助。
您可以尝试以下方法。
警告:我没有测试这段代码
while(true)
{
System.out.println("Are you single or married? \n 1 - Single \n 2 - Married");
status = in.nextInt(); // allow input for status
if(status==1 || status==2)
break;
}