[英]How can I execute a section of code by asking the user in the console if they want to repeat the calculation
I have written code that performs calculations by entering the console and now I want to ask the user if they want to perform this again by entering "Y" or "N" in the console.我已经编写了通过进入控制台执行计算的代码,现在我想询问用户是否要通过在控制台中输入“Y”或“N”再次执行此操作。
I solved this part with a simple if statement, but now I want to execute the whole code above again in case the user enters "Y".我用一个简单的 if 语句解决了这部分,但现在我想再次执行上面的整个代码,以防用户输入“Y”。 Does anyone have a suggestion for this problem?
有人对这个问题有建议吗?
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
}
}
There are a few ways you could repeat the code above, depending on what you're trying to accomplish.有几种方法可以重复上面的代码,具体取决于您要完成的任务。 One way would be to use a while loop that continues to execute the code as long as the user enters "Y".
一种方法是使用 while 循环,只要用户输入“Y”就继续执行代码。 Here's an example:
这是一个例子:
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");
Another way would be to use a do-while loop, like this:另一种方法是使用 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");
It's a good idea to wrap up the code that needs to be repeated in a function, so it could be easily called multiple times.最好将需要重复的代码封装在一个function中,这样可以方便地多次调用。
You also could use recursion, which is a technique that involves a function calling itself.您还可以使用递归,这是一种涉及 function 调用自身的技术。 This would also let you wrap up the code that needs to be repeated in a single function, but it can be more tricky to implement and can lead to stack overflow if not implemented correctly.
这也可以让您将需要重复的代码包装在一个 function 中,但实现起来可能更棘手,如果实现不正确,可能会导致堆栈溢出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.