Java中的InputMisMatchException是什么?如何处理它?
从Java 1.5开始引入Scanner类。此类接受File、InputStream、Path和String对象,使用正则表达式逐个读取所有基本数据类型和字符串(来自给定的源)。
使用此类提供的nextXXX()方法(例如nextInt()、nextShort()、nextFloat()、nextLong()、nextBigDecimal()、nextBigInteger()、nextLong()、nextShort()、nextDouble()、nextByte()、nextFloat()、next())从源读取各种数据类型。
当您使用Scanner类从用户获取输入时,如果传递的输入与方法不匹配,则会抛出InputMisMatchException异常。例如,如果您使用nextInt()方法读取整数数据,而传递的值是字符串,则会发生异常。
示例
import java.util.Scanner;
public class StudentData{
int age;
String name;
public StudentData(String name, int age){
this.age = age;
this.name = name;
}
public void display() {
System.out.println("Name of the student is: "+name);
System.out.println("Age of the student is: "+age);
}
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your age: ");
int age = sc.nextInt();
StudentData obj = new StudentData(name, age);
obj.display();
}
}运行时异常
Enter your name: Krishna Enter your age: twenty Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at july_set3.StudentData.main(StudentData.java:20)
处理输入不匹配异常
处理此异常的唯一方法是确保在传递输入时输入正确的值。建议在使用Scanner类从用户读取数据时,详细说明所需的值。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP