2016-03-22 21 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()'を呼び出して、あなたは1 'char'を取得しているので。あなたは 'Scanner'を構築し、' nextInt() 'メソッドを呼び出す必要があります。' Scanner scan = new Scanner(System.in); i = scan.nextInt(); ' – Majora320

+1

' System.in.read() 'は次の** byte **をとります。大きな違いがあります。 –

+1

デバッガを使用するか、変数を出力して、テストなしで尋ねる前にコードが実際に行っていることを確認してください。あなたがそうした場合は、それらを質問に書いてください。 – Nier

答えて

1

System.in.read()がタイプされた文字を表すcharオブジェクトを返しますので。 intにキャストすると、入力された実際の整数の代わりに、全く異なる値を持つcharオブジェクトが返されます。

この問題を解決するには、nextInt()メソッドが完備されたScannerクラスを使用する必要があります。それは無効な入力に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

関連する問題