【问题标题】:How to catch user input if it is anything else but int?如果它不是 int,如何捕获用户输入?
【发布时间】:2021-01-15 09:03:06
【问题描述】:

所以我现在正在创建一个井字游戏,除了 int 之外,我真的不知道如何处理其他任何东西。假设用户输入是一个字符串——程序会抛出一个错误。我实际上希望它抓住它并说“这不是 1 到 9 之间的数字”。我该怎么做?

int nextPlayerTurn= scan.nextInt();
            while (playerPosition.contains(nextPlayerTurn) ||computerPosition.contains(nextPlayerTurn)
                    || nextPlayerTurn>= 10 || nextPlayerTurn<= 0 ) {
                System.out.println("Position already taken! Please input a valid number (between 1 and 9) ");
                nextPlayerTurn= scan.nextInt();

【问题讨论】:

标签: java error-handling


【解决方案1】:

您可以使用try catch 方法或if else 条件。

使用if else

if(scan.hasNextInt()){
    int nextPlayerTurn = scan.nextInt();
    if(nextPlayerTurn < 0 || nextPlayerTurn > 10){
        System.out.println("this is not a number between 1 and 9");
    }else{
        //do something
    }
}else{
    System.out.println("this is not a number between 1 and 9");
}

使用try catch

try{
    int nextPlayerTurn = scan.nextInt();
    if(nextPlayerTurn < 0 || nextPlayerTurn > 10){
        System.out.println("this is not a number between 1 and 9");
    }else{
        //do something
    }
}catch(InputMismatchException e){
    System.out.println("this is not a number between 1 and 9");
}

不过,您也可以使用一种方法来检查InputMismatchException
还要检查Exception Handling Java

【讨论】:

    【解决方案2】:

    如果你使用nextInt()并且用户输入了一个字符串,就会抛出InputMismatchException。

    这是一种处理方式:

    try {
        scan.nextInt();
    }catch (InputMismatchException e) {
        System.err.println("this is not a number between 1 and 9");
    }
    

    请注意,在用户输入 int 之前,您必须重复使用 nextInt()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多