![](/img/trans.png)
[英]After asking the user for how many questions they want, how can I get my code to show that number of random problems?
[英]How can I execute a section of code by asking the user in the console if they want to repeat the calculation
我已经编写了通过进入控制台执行计算的代码,现在我想询问用户是否要通过在控制台中输入“Y”或“N”再次执行此操作。
我用一个简单的 if 语句解决了这部分,但现在我想再次执行上面的整个代码,以防用户输入“Y”。 有人对这个问题有建议吗?
System.out.println("Wollen Sie die Rechnung nocheinmal ausführen? Y / N");
String yesorno2 = StdIn.readString();
if (yesorno2.equals("Y")) {
//Should repeat the code above
} else {
System.out.println("Auf Wiedersehn");
//Should say the text above and end the code
}
}
有几种方法可以重复上面的代码,具体取决于您要完成的任务。 一种方法是使用 while 循环,只要用户输入“Y”就继续执行代码。 这是一个例子:
while (yesorno2.equals("Y")) {
// code to repeat goes here
System.out.println("Wollen Sie die Rechnung nocheinmal ausführen? Y / N");
yesorno2 = StdIn.readString();
}
System.out.println("Auf Wiedersehn");
另一种方法是使用 do-while 循环,如下所示:
do {
// code to repeat goes here
System.out.println("Wollen Sie die Rechnung nocheinmal ausführen? Y / N");
yesorno2 = StdIn.readString();
} while (yesorno2.equals("Y"));
System.out.println("Auf Wiedersehn");
最好将需要重复的代码封装在一个function中,这样可以方便地多次调用。
您还可以使用递归,这是一种涉及 function 调用自身的技术。 这也可以让您将需要重复的代码包装在一个 function 中,但实现起来可能更棘手,如果实现不正确,可能会导致堆栈溢出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.