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; 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 Student s1 = new StudentPT(stuNo, name, english, math, Java, testScore); System.out.println(s1.toString()); } else if (fields[5].equals("SystemFramework")) { // 学生SJ Student s2 = new StudentSJ(stuNo, name, english, math, Java, testScore); System.out.println(s2.toString() + " task:SystemFramework"); sum2 = s2.sum(); } else if (fields[5].equals("GroupLeader")) { // 学生ZZ Student s3 = new StudentZZ(stuNo, name, english, math, Java, testScore); System.out.println(s3.toString() + " duty:GroupLeader"); 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"); } } } 如何将三组数据的输出循序更改
时间: 2023-12-10 18:03:24 浏览: 87
Exception in thread “main“ java.util.InputMismatchException.pdf
可以改变输入数据的顺序,或者修改代码中的循环结构。下面是一种修改循环结构的方式,将每组数据的输入和输出放在一个循环中,循环内部根据输入的第一个字段判断学生类型并输出对应信息:
```
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;
int i = 1;
while (i <= 3) { // 循环三次输入和输出
System.out.println("请输入第" + i + "个学生信息:");
String line = in.nextLine();
String[] fields = line.split(" ");
stuNo = fields[0];
name = fields[1];
english = Double.parseDouble(fields[2]);
math = Double.parseDouble(fields[3]);
Java = Double.parseDouble(fields[4]);
if (fields.length == 5) {
Student s1 = new StudentPT(stuNo, name, english, math, Java, testScore);
System.out.println(s1.toString());
} else if (fields[5].equals("SystemFramework")) {
Student s2 = new StudentSJ(stuNo, name, english, math, Java, testScore);
System.out.println(s2.toString() + " task:SystemFramework");
sum2 = s2.sum();
} else if (fields[5].equals("GroupLeader")) {
Student s3 = new StudentZZ(stuNo, name, english, math, Java, testScore);
System.out.println(s3.toString() + " duty:GroupLeader");
sum3 = s3.sum();
}
i++;
}
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");
}
}
}
```
这样修改后,每次输入完一组数据后就会立即输出对应的信息,再进入下一轮输入。
阅读全文