Java程序中Scanner读取字符串异常:输入整句仅输出首词求解
问题原因分析
问题出在java.util.Scanner类的不同读取方法行为差异上:
nextInt()和nextDouble()这类方法仅读取匹配数值格式的内容,不会处理输入末尾的换行符,这个换行符会残留在输入缓冲区中。- 后续调用
nextLine()时,它会读取从当前缓冲区位置到下一个换行符之间的所有内容——也就是之前残留的空换行,导致变量s实际存储的是空字符串,而非你输入的完整句子。如果是在同一行输入数值和句子,nextLine()会读取数值后的剩余部分,但分多行输入时就会直接拿到空值,看起来像是没读取到句子。
解决方法
有两种常用修复方式:
方式一:提前消耗残留的换行符
在调用nextLine()读取句子前,额外调用一次scan.nextLine()清空缓冲区里的换行符:
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i = scan.nextInt(); double d = scan.nextDouble(); // 消耗数值读取后残留的换行符 scan.nextLine(); String s = scan.nextLine(); System.out.println("String: " + s); System.out.println("Double: " + d); System.out.println("Int: " + i); } }
方式二:统一使用nextLine()读取所有输入
先通过nextLine()读取每一行输入,再手动转换为对应数值类型,彻底避免换行符残留问题:
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i = Integer.parseInt(scan.nextLine()); double d = Double.parseDouble(scan.nextLine()); String s = scan.nextLine(); System.out.println("String: " + s); System.out.println("Double: " + d); System.out.println("Int: " + i); } }
内容的提问来源于stack exchange,提问作者Ansuman Pany
相关产品推荐
相关产品推荐

