簡體   English   中英

如何通過詢問控制台中的用戶是否要重復計算來執行一段代碼

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM