简体   繁体   中英

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.

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". 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". 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 {
    // 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.

You also could use recursion, which is a technique that involves a function calling itself. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM