2014-09-19 63 views
0

我有麻煩在底部我試圖設置退出哨兵退出鍵.. 即時通訊不知道我到底應該如何做到這一點。哨兵問題與循環,以允許進入退出結束程序在java

int number;

do 
    { 

      Scanner Input = new Scanner(System.in); 
    System.out.print("Enter a positive integer or q to quit program:"); 
     number = Input.nextInt(); 
    } 
    while(number >= 0); 

    do 
    { 

      Scanner Input = new Scanner(System.in); 
    System.out.print("Input should be positve:"); 
     number = Input.nextInt(); 
    } 
    while(number < 0); 

      do 
      { 

      Scanner quit = new Scanner(System.in); 
      System.out.print("Enter a positive integer or quit to end program"); 
      input = quit.nextstring(); 


      } 
      while (!input.equals(quit))//sentinel value allows user to end program 
      { 
      quit = reader.next() 

回答

1

一對夫婦提示:

  • 不要初始化新的掃描儀每一次迭代,這將是非常昂貴 。
  • 請注意,如您所寫,如果用戶輸入負數 ,他們無法返回到第一個while循環以保持 輸入正數。
  • 我假設你想要這一切,而 循環,而不是三個,或這些行動將不得不在 序列執行突破所有3個哨兵條件。
  • System.out.print()不會添加新行,這看起來很尷尬。

工作這些假設,這裏有一個定點變量endLoop如果退出條件滿足的是被重置,即用戶輸入「退出」版本。如果他們輸入一個負數,「輸入應該是正數」信息將被打印,然後循環將重新開始,如果他們輸入一個正數,那麼什麼都不會發生(我標記了在哪裏添加任何動作)和循環將重新開始。我們只在檢查到它不是'quit'後纔將輸入(它是一個String)轉換爲一個int,因爲如果我們試圖將一個String(如'quit')轉換爲int,程序將會崩潰。

Scanner input = new Scanner(System.in); 
boolean endLoop = false; 
String line; 
while (!endLoop) { 
    System.out.print("Enter a positive integer or 'quit' to quit program: "); 
    line = input.nextLine(); 
    if (line.equals("quit")) { 
    endloop = true; 
    } else if (Integer.parseInt(line) < 0) { 
    System.out.println("Input should be positive."); 
    } else { 
    int number = Integer.parseInt(line); 
    //do something with the number 
    } 
} 

編輯爲使用'quit'而不是0作爲終止條件。 請注意,如果用戶輸入的不是數字或「退出」,該程序將崩潰。

+0

是它我在找什麼,但我需要結束循環爲q而不是0 .. does布爾接受這兩種類型? – 2014-09-20 21:18:43

+0

'boolean'類型表示真或假,而不是其他類型。你想檢查'input.nextLine()'用戶輸入,它不存儲在'endLoop',這是你的哨兵變量。我會更新我的答案,以顯示如何檢查'q'。 – legendof 2014-09-22 17:26:10

+0

我建議刷新Java類型:http://docs.oracle.com/javase/tutorial/java/generics/types.html – legendof 2014-09-22 17:33:49