public class StudentDemo { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 判断类型并循环输入 String stuNo, name, str; double english, math, Java, testScore = 1.0; double sum2 = 0, sum3 = 0; Student s1 = null; Student s2 = null; Student s3 = null; while (in.hasNext()) { String line = in.nextLine(); String[] fields = line.split(" "); //字符串 line 按照空格分隔符进行拆分,拆分后的结果存储在一个名为 fields 的字符串数组中 stuNo = fields[0]; //取 fields 数组的第一个元素,即该语句将 fields 数组的第一个元素的值赋给了变量 stuNo name = fields[1]; english = Double.parseDouble(fields[2]); math = Double.parseDouble(fields[3]); Java = Double.parseDouble(fields[4]); if (fields.length == 5) { //学生PT s1 = new StudentPT(stuNo, name, english, math, Java, testScore); System.out.println(s1.toString()); } else if (fields[5].equals("SystemFramework")) { //学生SJ s2 = new StudentSJ(stuNo, name, english, math, Java, testScore); System.out.println(s2.toString()); sum2 = s2.sum(); } else if (fields[5].equals("GroupLeader")) { //学生ZZ s3 = new StudentZZ(stuNo, name, english, math, Java, testScore); System.out.println(s3.toString()); sum3 = s3.sum(); } else { break; } } //比较大小 double max = Math.max(sum2,sum3); if(max == sum2){ System.out.println("Lisi's total score is more than Wangwu"); }else if(max == sum3){ System.out.println("Lisi's total score is less than Wangwu"); } } }当第一组1001 Zhangsan 89 87 84 1002 输入时,最后一项为回车,怎么解决
时间: 2023-12-10 19:03:34 浏览: 68
Exception in thread “main“ java.util.InputMismatchException.pdf
你可以在读取输入时使用 `in.nextLine()` 代替 `in.next()`,这样可以读取整个输入行,包括回车符。修改后的代码如下:
```
while (in.hasNextLine()) { // 使用 hasNextLine() 替换 hasNext()
String line = in.nextLine();
if (line.equals("")) { // 如果是空行则跳过
continue;
}
String[] fields = line.split(" ");
// ...
}
```
阅读全文