Java Scanner nextLine() 读取空字符串问题解析

在使用Java Scanner类读取控制台输入时,你可能会遇到 nextLine() 方法读取到空字符串的情况,特别是当它跟在 nextInt() 这样的方法之后。

问题代码示例:javapublic class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i = 0; i < n; i++) { String str = sc.nextLine(); System.out.println(6+str.substring(6,11)); } }}

这段代码的问题在于,sc.nextInt() 只读取整数部分,不会读取输入流中的换行符。当程序执行到 sc.nextLine() 时,它会读取上一次输入遗留的换行符,导致 str 变量的值为空字符串。

解决方案:

为了解决这个问题,我们需要在调用 sc.nextInt() 后添加一个 sc.nextLine() 语句,用于消耗掉输入流中的换行符。

修改后的代码:javapublic class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); // 消耗换行符 for (int i = 0; i < n; i++) { String str = sc.nextLine(); System.out.println(6 + str.substring(6, 11)); } }}

通过添加 sc.nextLine(); 语句,我们可以确保在循环开始之前正确读取输入,避免出现空字符串的问题。

Java Scanner nextLine() 读取空字符串问题解析

原文地址: http://www.cveoy.top/t/topic/BW7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录