2016-10-29 16 views
0

我正在試圖製作一個基於文本的搖滾紙剪刀。我希望玩家選擇他們想玩的內容,例如「用戶回覆/用戶回覆」中的「最佳(用戶回覆/ 2 + 1)」,那麼它會要求驗證他們是否想玩這個號碼。如果他們說是,它會繼續比賽,如果不是這樣,它會循環備份並讓他們選擇另一個號碼,我還有一個提醒他們可以選擇是或否的選項。當他們最初被問到時,信件不起作用,他們被要求再次嘗試。在第二個循環(當你說不),如果你輸入一個字符串而不是一個Int它崩潰。在這裏,我有什麼。使用字符串而不是整數進行循環和捕獲? (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」太檢查字符串的用戶投放是一個數字,如果不,做了一段時間

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); 

所以

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

您可以提取你的循環的方法,並在第二種情況下使用它。

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); 
} 
相關問題