Java程序InputMismatchException抛出及Scanner读取异常问题
Scanner输入读取异常与内容错位问题解析
问题描述
我编写的Java程序在特定输入下会抛出InputMismatchException,同时sc.nextLine()的读取结果不符合预期。程序代码如下:
import java.util.*; public class InputInJava { public static void main(String [] args){ Scanner sc = new Scanner(System.in); String name = sc.next(); String fName = sc.nextLine(); int number = sc.nextInt(); float Fnumber = sc.nextFloat(); double Dnumber = sc.nextDouble(); short Snumber = sc.nextShort(); byte Bnumber = sc.nextByte(); long Lnumber = sc.nextLong(); System.out.println(name); System.out.println(fName); System.out.println(number); System.out.println(Fnumber); System.out.println(Dnumber); System.out.println(Snumber); System.out.println(Bnumber); System.out.println(Lnumber); } }
尝试过两种输入:
第一种输入:
String String 1 1 1
第二种输入:
String String 1 1 1 1 1 1 1
第二种输入得到的输出:
String String 1 1 1.0 1.0 1 1 1
疑惑点:为什么sc.nextLine()只读取到空格和1就结束,后续输入被其他读取方法获取?
原因分析
核心问题在于Scanner的next()和nextLine()方法的行为差异:
next()方法仅读取到第一个空白符(空格、换行符、制表符等)就停止,读取完成后光标停留在该空白符位置,不会跳过它。nextLine()方法读取从当前光标位置到下一个换行符(\n)之间的所有内容,读取完成后会跳过换行符,光标移至下一行开头。
在你的代码流程中:
- 执行
String name = sc.next();时,输入的第一个String被读取,光标停留在第一个String后的空格处。 - 紧接着调用
sc.nextLine(),它从当前光标位置(空格)开始,读取到该行的换行符为止,也就是读取了String 1(包含开头的空格),这就是fName的内容。 - 后续的
sc.nextInt()、sc.nextFloat()等方法会自动跳过前面的空白符(包括换行符),直接读取对应数值类型,所以后续输入会被这些方法依次获取。如果输入的数值数量不足,就会抛出InputMismatchException——比如第一种输入里,你只提供了部分数值,后续方法找不到对应类型的输入就会报错。
解决方法
要解决这个问题,需要在next()之后、nextLine()之前,手动处理掉next()留下的空白符或换行符,有两种常用方案:
方案1:在next()后调用空的nextLine()消费剩余内容
String name = sc.next(); sc.nextLine(); // 消费掉next()留下的空白和换行符 String fName = sc.nextLine();
方案2:全程使用nextLine()读取,手动转换数据类型
String name = sc.nextLine(); String fName = sc.nextLine(); int number = Integer.parseInt(sc.nextLine()); float Fnumber = Float.parseFloat(sc.nextLine()); double Dnumber = Double.parseDouble(sc.nextLine()); short Snumber = Short.parseShort(sc.nextLine()); byte Bnumber = Byte.parseByte(sc.nextLine()); long Lnumber = Long.parseLong(sc.nextLine());
两种方案都能保证输入被正确读取,避免内容错位或抛出异常的情况。
内容的提问来源于stack exchange,提问作者rahul kumar
相关产品推荐
相关产品推荐

