我是java的初學者,我想再回圈一次,但我不知道怎么做。我嘗試了一個while回圈,但它并不能很好地作業,它會列印兩個代碼塊。應該發生的是,當我鍵入“quit、Quit 或 QUIT”時,它應該終止。相反,它還會列印訊息“未能終止程式”。我該怎么辦?我還嘗試了一個 if 陳述句,它作業正常,但如果條件失敗,我不知道如何回圈它。
import java.util.Scanner;
public class fortytwo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Hi there!");
String quit = scanner.next();
while (quit.equals("quit") || quit.equals("QUIT") || quit.equals("Quit")) {
System.out.println("You terminated the program");
break;
}
System.out.println("You failed to terminate the program.\n To quit, type (quit), (Quit), or (QUIT)");
scanner.close();
}
}
uj5u.com熱心網友回復:
您正在使用回圈而不需要它。也break只是退出回圈,但在回圈后繼續執行。用 if/else 替換 while:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Hi there!");
String quit = scanner.next();
if(quit.toLowerCase().equals("quit")) {
System.out.println("You terminated the program");
} else {
System.out.println("You failed to terminate the program.\n To quit, type (quit), (Quit), or (QUIT)");
}
scanner.close();
}
這不會再次提示您輸入第二個輸出提示的輸入,但您的代碼也不會。
uj5u.com熱心網友回復:
回圈的條件是檢查while quit不等于"quit"(不管大小寫),所以"You failed to terminate the program..."應該在回圈體中列印訊息,直到輸入適當的命令。
此外,quit可以省略賦值,并且equalsIgnoreCase建議在常量/文字值上呼叫該方法,因為在一般情況下它有助于避免NullPointerException.
while (!"quit".equalsIgnoreCase(scanner.next())) {
System.out.println("You failed to terminate the program.\n To quit, type (quit), (Quit), or (QUIT)");
}
System.out.println("You terminated the program");
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411440.html
標籤:
上一篇:如何遍歷列并按組檢查條件
