簡體   English   中英

如何手動退出while循環(java)

[英]How to manually exit a while loop (java)

該代碼將從控制台獲取用戶輸入,並根據輸入是否為Integer轉到兩個位置之一。 該例外被捕獲,然后處理再次閱讀它把它弄出來的流。 (不確定Scanner是否算作流,但是我知道沒有input.next()它將永遠不會離開該部分)。

因此,我想知道的是,如果使用特定輸入到達MismatchException,如何退出循環。 我測試過,如果(bad_input ==任何東西),它原來我從來沒有真正到達那里。 我在該塊中嘗試了一些從未執行過的打印語句。 將不勝感激。

解決了

不知道如何關閉的問題,但是這已經解決了。 我錯誤地使用==檢查兩個字符串。 正確的方法是使用bad_input.equals(“X”)。

public static void main(String[] args){
  //read input from console
  Scanner input = new Scanner(System.in);

  boolean loop = true;

  while(loop){
    //inputting "1 2 d 1" will evaluate each term separately and output at once
    try{

      //choice = console input only in INTEGER
      int choice = input.nextInt();
      System.out.println("Input was " + choice);

    } catch (InputMismatchException ex){
      //here if input != INTEGER

      String bad_input = input.next();
      System.out.println("Bad Input: " + bad_input);

      //need to figure out how to exit loop!!
      if(bad_input == "x"){
           loop = false;
           return;
      }
      continue;
    }
  }
}

在java中,字符串比較使用的是equals函數“ ==”可能不起作用

更改

if (bad_input == "x") {
    loop = false;
    return;
}

if (bad_input.equals("x")) {
    loop = false;
    return;
}

嘗試使用break。

if(condition)
    break;

break; 將立即退出循環。 不過,您正在執行的操作也應該起作用。 我不確定您是否需要if語句,僅當輸入不是整數時,才會執行整個catch塊。

好吧,我認為你需要使用

 if(bad_input.equals("x")){
       loop = false;
       return;
  }

==檢查相同的參考

.equals檢查相同的值

http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

可能是您應該使用equalsIgnoreCase方法。

if (bad_input.equalsIgnoreCase("x")) {

而要以除整數之外的任何其他值退出循環,只需使用break即可

catch (InputMismatchException ex) {
                // here if input != INTEGER

                String bad_input = input.next();
                System.out.println("Bad Input: " + bad_input);

                break;
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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