2016-10-29 3 views
0

私は、テキストベースのロックペーパーはさみを作ろうとしています。私はプレイヤーにプレイしたいものを選択させたいと思っています。たとえば、「ユーザー応答/ 2 + 1」のうち、「ユーザー応答/ユーザー応答」(最高)を再生したい場合は、確認を求めます。彼らが「はい」と答えた場合は、そのスコアでゲームを続行します。もしそれがループバックされずに別の番号を選ぶことができれば、私はそれを思い出させます。彼らが最初に尋ねられるとき、手紙は効き目がなく、彼らは再度試みるように頼まれます。 2番目のループの周りで(あなたがいいえと言うとき)、Intの代わりにStringを入力するとクラッシュします。ここに私が持っているもの。ループを作成し、intの代わりにStringsを使用してキャッチしますか? (java)

System.out.println("Best of:"); 
    String line = userIn.nextLine(); 
    while (true) { 
     if (line.length() > 0) { 
      try { //try catch to stop strings for a response 
       bestOf = Integer.parseInt(line); 
       break; 
      } catch (NumberFormatException e) { 

      } 
     } 
     System.out.println("Please enter a number"); 
     line = userIn.nextLine(); 
    } 
    System.out.println("Okay, so you want to play best " + (bestOf/2 + 1) + " of " + bestOf + "?"); 
    String response2 = userIn.nextLine(); 
    while (true) { 
     if (response2.contains("n")) { 
      System.out.println("What do you wish to play to then, " + name + "?"); 
      bestOf = userIn.nextInt(); 
      response2 = "y"; 
     } else if (response2.contains("y") || response2.contains("Y")) { 
      winScore = (bestOf/2 + 1); 
      System.out.println("Okay, best " + (bestOf/2 + 1) + " of " + bestOf + " it is!"); 
      break; 
     } else { 
      System.out.println("That's not a valid response! Try again."); 
      response2 = userIn.nextLine(); 
     } 
    } 
+1

あなたのコードを持っている問題であり、どのような質問は、質問を編集して、期待される出力が何であるかを追加し、明確ではないとの現在の出力は何ですか?与えられた入力? – Ravikumar

答えて

0

代わりに文字列を使用するのparseIntを使用する、つまり入力はそれらが文字列のユーザープットがあれば数であるかどうかをチェックあまりにも機能「ISNUMBER」を使用する(数であっても)文字列としてそれを取りますあなたが方法として、あなたのループを抽出し、同様に第二の場合にはそれを使用することができますので、

 public static boolean isNumeric(String str) { 
    try { 
     double d = Double.parseDouble(str); 
    } catch (NumberFormatException nfe) { 
     return false; 
    } 
    return true; 
} 
0

、しばらく

System.out.println("Best of:"); 
    String line = userIn.nextLine(); 
    String aux = line; 
    do{ 
      if (line.length() > 0) 
      aux = line; 

     if(!isNumeric(aux)){ 
      System.out.println("Please enter a number"); 
      line = userIn.nextLine();     
     } 
    }while(!isNumeric(aux)); 

    bestOf = Integer.parseInt(aux); 

をしません。

private Integer readInt(Scanner scanner){ 
    String line = scanner.nextLine(); 
    while (true) { 
     if (line.length() > 0) { 
      try { //try catch to stop strings for a response 
       Integer result = Integer.parseInt(line); 
       return result; 
      } catch (NumberFormatException e) { 

      } 
     } 
     System.out.println("Please enter a number"); 
     line = scanner.nextLine(); 
    } 
} 

またはより良い:

private Integer readInt(Scanner scanner){ 
    Integer result; 
    do{ 
     try{ 
      return scanner.nextInt(); 
     } catch (InputMismatchException e){ 
      scanner.nextLine(); 
      System.out.println("Please enter a number"); 
     } 
    } while (true); 
} 
関連する問題