标签:get system 去掉 oid inpu cores es2017 返回 code
在课后习题中用到了以下代码
1 public static void main(String[] args) { 2 System.out.print("输入学生人数:"); 3 int student_number = input.nextInt(); 4 System.out.print("输入学生成绩:"); 5 String scores = input.nextLine(); 6 int[] score_arrayi = getScore(scores); 7 int max_score = maxScore(score_arrayi); 8 grade(score_arrayi,max_score); 9 }
可是在具体输入的时候会出现以下问题
也就是在输入学生人数4之后,按下回车。无法输入学生成绩,直接跳过
1 String scores = input.nextLine();
后来查找资料后得知:
next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。简单地说,next()查找并返回来自此扫描器的下一个完整标记。完整标记的前后是与分隔模式匹配的输入信息,所以next方法不能得到带空格的字符串
而nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。
意思就是说,nextInt()读到有效值后就结束,输完数字后按的回车符还存在,nextLine()读取到回车符就直接结束,所以结果就类似于跳过了该条输入语句
因此为了解决这个问题,可以在nextInt()后面再加上一个nextLine()完善代码如下
1 public static void main(String[] args) { 2 System.out.print("输入学生人数:"); 3 int student_number = input.nextInt(); 4 System.out.print("输入学生成绩:"); 5 input.nextLine(); 6 String scores = input.nextLine(); 7 int[] score_arrayi = getScore(scores); 8 int max_score = maxScore(score_arrayi); 9 grade(score_arrayi,max_score); 10 }
标签:get system 去掉 oid inpu cores es2017 返回 code
原文地址:http://www.cnblogs.com/Charles9703/p/7612820.html