Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果用户输入了错误的答案,如何跳回if语句的开头_Java_If Statement_Input - Fatal编程技术网

Java 如果用户输入了错误的答案,如何跳回if语句的开头

Java 如果用户输入了错误的答案,如何跳回if语句的开头,java,if-statement,input,Java,If Statement,Input,代码如下: if (g1 == 6) { System.out.println("Correct! Proceed to the next challenge"); } else { System.out.println("That is incorrect, please try again"); } 例如,如果他们输入“4”进行猜测,我如何允许他们重试? 基本上,如何回到if语句的开头?这就是而循环是为之设计的 String g1 = ""; try { Inpu

代码如下:

if (g1 == 6) {
   System.out.println("Correct! Proceed to the next challenge");
} 
else {  
   System.out.println("That is incorrect, please try again");
}
例如,如果他们输入“4”进行猜测,我如何允许他们重试?
基本上,如何回到
if
语句的开头?

这就是
循环是为之设计的

String g1 = "";
try {
    InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
    do {
      g1 = in.readLine();
      if (g1 == 6) {
        System.out.println("Correct! Proceed to the next challenge");
      } else {
        System.out.println("That is incorrect, please try again");
      }
    } while(g1 != 6);
} catch (Exception e) {
System.out.println("Error! Exception: "+e); 
}
在学习编程时,重点考虑通过
if
while
构造的指令序列。如果你得到一个建议,给你一些细节,阅读它。理解它

想想它在做什么,你想让它做什么——以及你如何弥合这一差距


如果你问为什么有些东西是“垃圾邮件”,你的想法应该转向导致垃圾邮件的循环内部需要发生的其他事情。

我这样做并运行了它。我输入了8,而不是再试一次,它不断地垃圾邮件“那是不正确的,请再试一次”,直到我停止它。我已经更新了答案。您所要做的就是在if/else验证之前,将读取用户输入的语句放入循环中。如果你觉得这有帮助,请投赞成票,并将答案标记为正确。快乐编码。