2016-08-03 88 views
1

我是新來的java編程,並正在測試一些我學到的東西,以便做出一個小猜謎遊戲。它可以工作,你可以通過它,但是當你得到第二個錯誤的數字後,你不會被告知你這個數字是低還是高。這是問題的一個例子:我的程序能夠正常工作,但不會打印時它應該是

Guess a number, 1 through 100: 
50 
Guess higher! 
75 
75 
Guess lower! 
65 
65 
Guess lower! 

這裏是代碼:如果塊

public static void main(String[] args) { 
    Random num = new Random(); 
    Scanner scan = new Scanner(System.in); 
    int rand; 
    boolean test; 
    int rand2; 
    int guess = 0; 

    rand = num.nextInt(100); 
    System.out.println("Guess a number, 1 through 100: "); 
    while(test = true){ 
     rand2 = scan.nextInt(); 
     if(rand == rand2){ 
      guess++; 
      if(guess < 19){ 
       System.out.println("Thats the correct number! And it only took: " + guess + " tries"); 
      }else{ 
       System.out.println("It took you: " + guess + " tries to guess the number!"); 
      } 

     }else if(rand < rand2){ 
      System.out.println("Guess lower! "); 
      guess++; 
      rand2 = scan.nextInt(); 
     }else if(rand > rand2){ 
      System.out.println("Guess higher! "); 
      guess++; 
      rand2 = scan.nextInt(); 
     } 
    } 
} 
+1

我看到的第一個問題,你看在這兩個條件下一個int和再次在環(所以第一個的開始猜測下/更高後忽略)。 – AxelH

+0

[什麼是調試器,它如何幫助我診斷問題?]可能的重複(http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-我診斷的 - 問題) – Raedwald

回答

0

在別的都刪除rand2 = scan.nextInt();並嘗試運行它。你的邏輯就像用戶輸入兩次,直到你得到正確的答案。

0

在進行下一個更低或更高檢查之前,您正在掃描另一個數字兩次。一旦進入if語句,另一個進入while循環的頂部。嘗試刪除if/else語句中的scan.nextInt()靜態方法調用,它應該像你想要的那樣工作。

while(test = true){ 
     rand2 = scan.nextInt(); 
     guess++; 
     if(rand == rand2){ 

      if(guess < 19){ 
       System.out.println("Thats the correct number! And it only took: " + guess + " tries"); 
       break; 
      }else{ 
       System.out.println("It took you: " + guess + " tries to guess the number!"); 
      } 
     }else if(rand < rand2){ 
      System.out.println("Guess lower! "); 
     }else if(rand > rand2){ 
      System.out.println("Guess higher! "); 
     } 
    } 
0

我有正確的爲你,看到如下:

public static void main(String[] args) { 

     Random num = new Random(); 
     Scanner scan = new Scanner(System.in); 
     boolean isOK = false; 
     int counter = 0; 

     int randNum = num.nextInt(100); 
     while(true) { 
      counter++; 

      int n = scan.nextInt(); 
      if(n == randNum) { 
       System.out.println("OK in " + counter + " times"); 
       isOK = true; 
      } else if(n > randNum) { 
       System.out.println("Lower"); 
      } else { 
       System.out.println("Higher"); 
      } 
     } 
    } 
相關問題