public class StudentDemo { public static void main(String[] args) { Scanner in = new Scanner(System.in); //学生一 String stuNo1 = in.next(); String name1 = in.next(); double english1 = in.nextDouble(); double math1 = in.nextDouble(); double Java1 = in.nextDouble(); double testScore1 = in.nextDouble(); Student s1 = new StudentPT(stuNo1,name1,english1,math1,Java1,testScore1); System.out.println(s1.toString()); //学生二 //学生三 } } interface Student{ String toString(); double sum(); //计算总成绩 double testScore(); //计算评测成绩注:评测成绩取三门课程成绩的平均分(保留2位小数) } class StudentPT implements Student{ private String stuNo; private String name; private double english; private double math; private double Java; private double testScore; private double max; public StudentPT (String stuNo,String name,double english,double math,double Java,double testScore){ this.stuNo =stuNo; this.name = name; this.english = english; this.math = math; this.Java = Java; this.testScore = testScore(); } public double sum(){ return english + math + Java; } public double testScore(){ return sum() / 3; } public String toString(){ return "stuNo:" + stuNo + " name:" + name + " english:%.1f" + english + " math:%.1" + math + " Java:%.1" + Java + "\n" + "testScore:%.2" + testScore; } } 无输出
时间: 2023-12-14 15:40:03 浏览: 30
这段代码存在一些问题,其中 `toString()` 方法中的格式化字符串不正确,应该使用 `%f` 而不是 `%`。此外,在 `toString()` 方法中应该使用 `String.format()` 方法来进行字符串的格式化,而不是直接使用字符串拼接。下面是修改后的代码:
```
public class StudentDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 学生一
String stuNo1 = in.next();
String name1 = in.next();
double english1 = in.nextDouble();
double math1 = in.nextDouble();
double java1 = in.nextDouble();
double testScore1 = in.nextDouble();
Student s1 = new StudentPT(stuNo1, name1, english1, math1, java1, testScore1);
System.out.println(s1.toString());
// 学生二
// 学生三
}
}
interface Student {
String toString();
double sum(); // 计算总成绩
double testScore(); // 计算评测成绩,取三门课程成绩的平均分(保留2位小数)
}
class StudentPT implements Student {
private String stuNo;
private String name;
private double english;
private double math;
private double java;
private double testScore;
private double max;
public StudentPT(String stuNo, String name, double english, double math, double java, double testScore) {
this.stuNo = stuNo;
this.name = name;
this.english = english;
this.math = math;
this.java = java;
this.testScore = testScore();
}
public double sum() {
return english + math + java;
}
public double testScore() {
return sum() / 3;
}
public String toString() {
return String.format("stuNo:%s name:%s english:%.1f math:%.1f java:%.1f\ntestScore:%.2f", stuNo, name, english, math, java, testScore);
}
}
```
在这个程序中,我们定义了一个 `Student` 接口来描述学生的基本信息和成绩情况,其中包括 `toString()`、`sum()` 和 `testScore()` 三个方法。然后我们又定义了一个 `StudentPT` 类来实现 `Student` 接口,其中包含了学生的具体信息和实现 `Student` 接口所需的方法。在 `main` 方法中,我们通过输入学生信息来创建 `StudentPT` 对象,并输出其信息。