2016-03-24 8 views
0

girişini sorar. Bu, kullanıcı girdisini kabul etmek için bir yöntem oluşturduğumdan beri böyle olmuştur. Önceden, tarayıcı döngüde idi, ancak farklı bir küçük soruna neden oluyordu. Ben statik giriş yöntemi kurtulmak için bunu biraz organize yenidenHerhangi bir nedenden dolayı, do-while döngüsüm ilk kez çalıştırıldığında, tarayıcı iki kez

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

Btw, orada iki if ifadesi olması için bir neden yok. Sadece her iki ifadeyi de ekleyiniz ... –

+1

Neler olup bittiğinden emin değilim, ancak tek bir akış üzerinde birden fazla tarayıcı oluşturmanın sizi sorunlara yol açacağından eminim. Yani döngüde veya birden çok kez çağrılacak bir yöntemde başlatma. –

+0

Ayrıca 'tahmin' oluşturmak ve dönmek için üç satır gerek yok. Yazabilirdiniz, int guess = scan.nexInt(); guess.'; veya daha iyisi scan.nextInt() 'i döndür. –

cevap

0

önce bu sorunu .. hiç ... Bu çalışır: Bir değişiklik System.out etrafında ise durum olduğunu düşünüyorum .println ("Hayır ..."); ...

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 + "]"); 
    } 
}