Java中sc.nextInt()后sc.nextLine()读取字符串失效问题求助
问题原因与解决方案
嘿,这个坑我之前踩过!咱们先搞明白为啥会这样:
当你用sc.nextInt()读取数字时,它只会提取输入里的数字部分,不会处理数字后面的换行符(就是你输入完数字按回车的那个\n)。接下来调用sc.nextLine()时,它会直接把这个残留的换行符当成一行输入,所以程序就直接跳过了你的字符串输入步骤,继续往下走了。
而sc.next()能正常工作是因为它会自动跳过开头的空白字符(包括换行符),只读取到下一个空白前的内容,所以它会等你输入有效的字符串才会继续。
下面给你两种靠谱的解决方案:
方案一:吃掉残留的换行符
在sc.nextInt()之后,额外调用一次sc.nextLine()来消耗掉那个多余的换行符,代码修改后如下:
public class project1 { public static void main(String[] args) { // 修正main方法必须的参数 Scanner sc = new Scanner(System.in); int n; char a; System.out.println("Enter \n 1 for counting the total number of vowels in it \n 2 for printing the first letter of each word in a string"); n = sc.nextInt(); sc.nextLine(); // 关键:吃掉数字后面的换行符 switch(n) { case 1: int count = 0; System.out.println("Input a string"); String str = sc.nextLine(); str = str.toLowerCase(); for(int i = 0; i < str.length(); i++) { a = str.charAt(i); if(a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') count++; } System.out.println("There are "+ count +" vowels in the string."); break; case 2: System.out.println("Input a string"); String str2 = sc.nextLine(); System.out.println("First letter of each word:"); // 新增:处理字符串开头和结尾的空格,避免数组越界 if(str2.length() > 0) { System.out.print(str2.charAt(0) + ", "); // 先打印第一个单词的首字母 for(int i = 0; i < str2.length()-1; i++) { a = str2.charAt(i); if(a == ' ') System.out.print(str2.charAt(i+1) + ", "); } } break; } sc.close(); // 记得关闭Scanner资源 } }
顺便帮你修正了main方法的必填参数,还有case2里可能出现的数组越界问题(比如字符串结尾是空格时,i+1会超出长度)。
方案二:统一用nextLine读取后转换
如果你不想处理换行符的麻烦,可以直接用sc.nextLine()读取所有输入,然后把数字字符串转换成int类型,这样就不会有残留字符的问题了:
// 替换原来的n = sc.nextInt(); System.out.println("Enter \n 1 for counting the total number of vowels in it \n 2 for printing the first letter of each word in a string"); String inputNum = sc.nextLine(); int n = Integer.parseInt(inputNum);
这种方法更通用,不管后续是读取字符串还是其他内容,都不会有奇怪的残留问题。
内容的提问来源于stack exchange,提问作者Krish
相关产品推荐
相关产品推荐

