2017-09-05 224 views
0

我想完成從一個在線Java教程的任務,我目前在關於While循環的問題。這是我的代碼:while循環在Java結束條件

import java.util.Scanner; 

public class bird { 
    public static void main(String[] args){ 
     Scanner bucky = new Scanner(System.in); 
     final String end = "END"; 
     String bird; 
     int amount; 

     System.out.println("What bird did you see in your garden? "); 
     bird = bucky.nextLine(); 

     while(!(bird.equals(end))){ 
      System.out.println("How many were in your garden? "); 
      amount = bucky.nextInt(); 

     } 
    } 
} 

我的問題是代碼意味着如果最終是由用戶,因此需要在While循環外部輸入的終止。但是如果沒有它在循環內部,它不會重複提出更多類型鳥類的問題。是否有辦法在循環中獲得第一個「你看到的是什麼鳥?」,同時如果滿足結束條件,還有退出循環的條件?

+0

你可能會尋找DO-同時,參見[_The而和do-while Statements_ tutorial](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html);雖然這也有你的具體用途問題。 –

+0

此代碼在邏輯上存在缺陷。 –

+0

這是關於掃描儀[見這裏](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo?noredirect=1&lq=1) – Pmanglani

回答

0

一種方式做到這一點(見代碼註釋):

public static void main(String[] args){ 
    Scanner bucky = new Scanner(System.in); 
    final String end = "END"; 
    String bird; 
    int amount; 

    while(true){ // loop "forever" 
     System.out.println("What bird did you see in your garden? "); 
     bird = bucky.nextLine(); 
     if (end.equals(bird)) { // break out if END is entered 
      break; 
     } 

     System.out.println("How many were in your garden? "); 
     amount = bucky.nextInt(); 
     bucky.nextLine(); // consume the newline character after the number 

     System.out.println("we saw " + amount + " of " + bird); // for debugging 
    } 
} 
0

試試這個快速解決方案:

import java.util.Scanner; 

public class Bird { 
    public static void main(String[] args){ 

     Scanner bucky = new Scanner(System.in); 
     System.out.println("What bird did you see in your garden? "); 

     while(!(bucky.nextLine().equalsIgnoreCase("END"))){ 
      System.out.println("How many were in your garden? "); 
      bucky.nextInt(); 
      System.out.println("What bird did you see in your garden? "); 
      bucky.nextLine(); 
     } 
    } 
}