簡體   English   中英

如何防止程序因輸入錯誤而崩潰

[英]How to prevent the programm for crashing because of a wrong input

當我在 1 到 9 之間選擇一個數字並在控制台中輸入一個數字時,該方法確實有效並做出了正確的移動。 但我的問題是如何避免在我輸入字母而不是數字時程序崩潰。

public class HumanPlayer {
   static Scanner input = new Scanner(System.in);

   public static void playerMove(char[][] gameBoard) {

       System.out.println("Wähle ein Feld 1-9");
       try {
           int move = input.nextInt();
           System.out.print(move);
           boolean result = Game.validMove(move, gameBoard);
           while (!result) {
               Sound.errorSound(gameBoard);
               System.out.println("Feld ist besetzt!");
               move = input.nextInt();
               result = Game.validMove(move, gameBoard);
           }

           System.out.println("Spieler hat diesen Zug gespielt  " + move);
           Game.placePiece(move, 1, gameBoard);
       } catch (InputMismatchException e) {
           System.out.print("error: not a number");
       }

   }
}

每個nextXYZ方法都有一個等效的hasNextXYZ方法,可以讓您檢查其類型。 例如:

int move;
if (input.hasNextInt()) {
    move = input.nextInt();
} else {
    // consume the wrong input and issue an error message
    String wrongInput = input.next();
    System.err.println("Expected an int but got " + wrongInput);
}

我認為它可以是這樣的,'a'仍然打印

System.out.println("expected input: [1-9]");
try {
    int move = input.nextInt();
} catch (Exception e) {
    e.printStackTrace();
    // do something with input not in [1-9]
}
System.out.println("a");

input.nextInt()在您輸入包含字母的InputMismatchException拋出InputMismatchException 此異常會導致程序崩潰。 使用 try-catch 塊來處理此異常,以免它影響您的程序:

try {
    int move = input.nextInt();
    System.out.print(move);
}
catch (InputMismatchException e) {
    System.out.print("error: not a number");
}

try-catch 塊是一個方便的工具,用於捕獲運行代碼時可能發生的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM