2016-03-22 144 views
1

我有一個Java任務,無法讓它工作。Java的猜測遊戲

我正在做1-100之間的猜謎遊戲。當我運行我的代碼時,它一直告訴我「太低」,無論是正確還是過高。

這裏是我的代碼:

public static void main(String[] args) throws java.io.IOException { 

    int i, ignore, answer = 64; 

    do { 
     System.out.println("I'm thinking of a number between 1 and 100."); 
     System.out.println("Can you guess it?"); 

     i = (int) System.in.read(); 

     do { 
      ignore = (int) System.in.read(); 
     } while (ignore != '\n'); 

     if (i == answer) System.out.println("**RIGHT**"); 
     else { 
      System.out.print("...Sorry, you're "); 

      if (i < answer) 
       System.out.println("too low"); 
      else 
       System.out.println("too high"); 
      System.out.println("Try again!\n"); 
     } 
    } while(answer != i); 
} 
+2

由於與調用'System.in.read()',你得到一個'char'。你應該構建一個'Scanner',並將其稱爲'nextInt()'方法,如下所示:'掃描儀掃描=新掃描儀(System.in); i = scan.nextInt();' – Majora320

+1

'System.in.read()'需要下一個**字節**而不是下一個** int **。有一個很大的區別 –

+1

你應該使用調試器,甚至只是打印變量,看看你的代碼實際上做什麼,然後再問你沒有任何測試。如果你這樣做,把它們寫入問題。 – Nier

回答

1

因爲System.in.read()返回表示這是輸入的字符char對象。將其轉換爲int將返回具有完全不同值的char對象,而不是輸入的實際整數。

要解決此問題,您應該使用Scanner類,該類有一個完美的nextInt()方法。它會拋出無效輸入InputMismatchException,所以如果你想錯誤處理,你應該抓住這一點。

這裏是一個工作(並稍微清理)你的代碼的版本:

import java.util.Scanner; 
import java.util.InputMismatchException; 

public class Guess { 
    public static void main(String[] args) { // No need to throw IOException 
     int input = -1, answer = 64; // Initialize input for if the user types 
            // in invalid input on the first loop 

     Scanner scan = new Scanner(System.in); 

     do { 
      System.out.println("I'm thinking of a number between 1 and 100."); 
      System.out.println("Can you guess it?"); 

      try { 
       input = scan.nextInt(); 
      } catch (InputMismatchException ex) { 
       System.out.println("Invalid Input!"); 
       continue; // Skips to the next loop iteration if invalid input 
      } 

      if (input == answer) 
       System.out.println("**RIGHT**"); 
      else { 
       System.out.println("...Sorry, you're too " + (input < answer ? "low" : "high")); 
       //^Ternary operator; you may not have learned this yet, but it 
       // just does a conditional return (if the value before the '?' is 
       // true, then return the value before the ':'; else return the 
       // value after.) 
       System.out.println("Try again!"); 
      } 
     } while (answer != input); 
    } 
} 
+0

這很好。非常感謝你的幫助。我不知道System.in.read()不會返回int。我從前的例子是使用字母而不是數字。我試圖修改該代碼。現在有道理! – Magdalina08

+0

不客氣! :3 – Majora320