字符串输入到整数字段的 InputMismatchException

InputMismatchException for String input into integer field

我在将非整数输入整数字段时遇到问题。我只是采取预防措施,这样如果另一个人 uses/works 在我的程序中,他们就不会得到这个 InputMismatchException

当我在 input 变量中输入非数字字符时,出现上述错误。有什么方法可以像 NullPointerException 那样对字符串进行补偿吗?

编辑此代码只是为了包含导致问题的相关部分。

import java.util.Scanner;

class MyWorld {

public static void main(String[] args) {

   Scanner user_input = new Scanner(System.in);

   int input = 0;   

   System.out.println("What is your age? : ");
   input = user_input.nextInt();
   System.out.println("You are: " +input+ " years old");

  }

}

这是一个 try-catch 块。如果您想确保不会使程序流停止,则需要使用它。

try { 
  input = user_input.nextInt();
}
catch (InputMismatchException exception) { //here you can catch that exception, so program will not stop
  System.out.println("Integers only, please."); //this is a comment
  scanner.nextLine(); //gives a possibility to try giving an input again
}

您可以添加一个 try-catch 块:

import java.util.Scanner;

class MyWorld {

public static void main(String[] args) {

   Scanner user_input = new Scanner(System.in);

   int input = 0;   

   System.out.println("What is your age? : ");

   try{
       input = user_input.nextInt();
   }catch(InputMisMatchException ex)
       System.out.println("An error ocurred");
   }

   System.out.println("You are: " +input+ " years old");

  }
}

如果你想让用户输入另一个 int,你可以创建一个布尔变量并创建一个 do-while 循环来重复它。如下:

boolean end = false;

//code

do
{
   try{
       input = user_input.nextInt();
       end = true;
   }catch(InputMisMatchException ex)
       System.out.println("An error ocurred");
       end = false;
       System.out.println("Try again");
       input.nextLine();
   }
}while(end == false);

使用 Scanner's next() 方法获取数据,而不是使用 nextInt()。然后使用 int input = Integer.parseInt(inputString); 将其解析为整数 parseInt() 方法抛出 NumberFormatException 如果它不是 int,你可以相应地处理它。

使用 hasNextInt().

进行测试
Scanner user_input = new Scanner(System.in);
System.out.println("What is your age?");
if (user_input.hasNextInt()) {
    int input = user_input.nextInt();
    System.out.println("You are " + input + " years old");
} else {
    System.out.println("You are a baby");
}

您可以使用 if 语句来检查是否 user_input hasNextInt()。如果输入是整数,则设置 input 等于 user_input.nextInt()。否则,显示一条消息,说明输入无效。这应该可以防止异常。

System.out.println("What is your age? : ");
if(user_input.hasNextInt()) {
    input = user_input.nextInt();
}
else {
    System.out.println("That is not an integer.");
}

这里有一些关于 hasNextInt() 来自 Javadocs 的更多信息。

附带说明,Java 中的变量名称应遵循 lowerMixedCase 约定。例如,user_input 应更改为 userInput