2016-03-24 51 views
0

這是因爲我創建了一個用於接受用戶輸入的方法。之前,掃描儀在循環中,但它造成了一個不同的小問題。我從來沒有這個問題之前..出於某種原因,我的第一次執行do-while循環時,掃描器要求輸入兩次

public static int input(){ 

    Scanner scan = new Scanner (System.in); 

    int guess; 
    guess = scan.nextInt(); 
    return(guess); 
} 

    public static void main(String[] args) { 

    do{ 
     if (firstPromptIsPrinted){ 
     System.out.println("Enter a number between 1 and 20."); 
     } 
     guess = input(); 

     if (secondPromptIsPrinted){ 
      System.out.println("Nope ;). "); 
     } 
     if (secondPromptIsPrinted){ 
      giveHint(guess, luckyNumber); 
     } 
     firstPromptIsPrinted = false; //Now 
     secondPromptIsPrinted = true; 

    } while (guess != luckyNumber); 
+0

順便說一句,沒有理由有兩個if語句在那裏。只要把這兩個陳述在第一個... –

+1

我不知道發生了什麼,但我敢肯定,在單個流上創建多個掃描儀會導致您遇到問題。因此,不要在循環或多次調用的方法中初始化它。 –

+0

也不需要三行來創建並返回'guess'。你可以寫'int guess = scan.nexInt();返回猜測;'或更好的只是'返回scan.nextInt()'。 –

回答

0

我重新組織了一點擺脫靜態輸入法......這工作:我覺得一個變化是周圍的System.out如果條件.println(「Nope ...」); ...

public class GuessGame { 

    Scanner scan = null; 

    public GuessGame() { 
     scan = new Scanner (System.in); 
    } 

    public int input() { 
     int ltheResult; 
     ltheResult = scan.nextInt(); 
     return ltheResult; 
    } 

    public static void main(String[] args) { 
     GuessGame ltheClass = new GuessGame(); 
     ltheClass.run(); 
    } 

    public void run() { 
     int guess = 0; 
     boolean firstPromptIsPrinted = true; 
     boolean secondPromptIsPrinted = false; 
     int luckyNumber = 10; 

     do { 
      if (firstPromptIsPrinted) { 
       System.out.println ("Enter a number between 1 and 20."); 
      } 
      guess = this.input(); 

      if (guess != luckyNumber) { 
       System.out.println ("Nope ;). "); 
      } 
      // if (secondPromptIsPrinted){ 
      // giveHint(guess, luckyNumber); 
      // } 
      firstPromptIsPrinted = false; // Now 
      secondPromptIsPrinted = true; 

     } 
     while (guess != luckyNumber); 
     System.out.println ("Yes luckyNumber is [" + luckyNumber + "]"); 
    } 
} 
相關問題