public class StudentDemo { public static void main(String[] args) { Scanner in = new Scanner(System.in); //判断类型并循环输入 String stuNo = in.next(); String name = in.next(); double english = in.nextDouble(); double math = in.nextDouble(); double Java = in.nextDouble(); String str = in.nextLine(); double testScore = 1.0; for(int i=0;i<3;i++){ //学生PT if(str.equals(" ")){//如果输入回车 Student s1 = new StudentPT(stuNo,name,english,math,Java,testScore); System.out.println(s1.toString()); } else if(str.equals("SystemFramework")){ Student s2 = new StudentPT(stuNo,name,english,math,Java,testScore); System.out.println(s2.toString() + " task:SystemFramework"); } else if(str.equals("GroupLeader")){ Student s3 = new StudentZZ(stuNo,name,english,math,Java,testScore); System.out.println(s3.toString() + " duty:GroupLeader"); } } 无输出
时间: 2023-12-10 16:03:16 浏览: 79
代码中有几个问题需要注意:
1. 在输入字符串 `str` 时,应该使用 `in.nextLine()` 而不是 `in.next()`,因为 `next()` 只会读取输入的下一个单词,若输入了回车键,则会被忽略掉。
2. 在循环中,每次都要重新读取 `str` 的值,否则会陷入死循环。
3. 循环的条件 `i<3` 是固定的,应该根据实际需求进行判断。
下面是修正后的代码:
```
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;
while (in.hasNextLine()) {
stuNo = in.next();
name = in.next();
english = in.nextDouble();
math = in.nextDouble();
Java = in.nextDouble();
in.nextLine(); // 读取回车符
str = in.nextLine();
// 学生PT
if (str.equals("")) {
Student s1 = new StudentPT(stuNo, name, english, math, Java, testScore);
System.out.println(s1.toString());
} else if (str.equals("SystemFramework")) {
Student s2 = new StudentPT(stuNo, name, english, math, Java, testScore);
System.out.println(s2.toString() + " task:SystemFramework");
} else if (str.equals("GroupLeader")) {
Student s3 = new StudentZZ(stuNo, name, english, math, Java, testScore);
System.out.println(s3.toString() + " duty:GroupLeader");
} else {
break;
}
}
}
}
```
此代码可以一直输入直到用户停止输入,若输入回车则会跳出循环。
阅读全文