我正在编写一个代码,其中包含学生姓名和成绩,并打印出他的名字总分和平均分数。我想让它更具功能性,允许用户输入名称和分数并获取所有信息。我可以尝试将其进一步扩展到类平均值,它允许输入多个单独的名称,分数和平均值,分别打印每个名称,然后显示班级平均值。这是第二个想法,因为我首先需要用户输入成绩和名称。
这是我到目前为止所拥有的。 我有一个单独的类来使一些事情更简单。
public class Student {
private String name;
private int numOfQuizzes;
private int totalScore;
public Student(String name){
this.name = name;
}
public String getName() {
return name;
}
public int getTotalScore() {
return totalScore;
}
public void addQuiz(int score) {
totalScore = totalScore + score;
numOfQuizzes++;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
然后我有主要方法:
public static void main(String[] args) {
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Student student = new Student(name);
student.addQuiz(96);
student.addQuiz(94);
student.addQuiz(93);
student.addQuiz(92);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
}
这是目前打印出来的内容:
What is your name? Tom
Students Name: Tom
Total Quiz Scores: 375
Average Quiz Score: 93.75
更新: 这就是我到目前为止所做的。我添加了一个循环并尝试使用我的学生课程,但它似乎无法使用该数组。
ArrayList<String> scores = new ArrayList<String>();
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Scanner scoreInput = new Scanner(System.in);
while (true) {
System.out.print("Please enter your scores (q to quit): ");
String q = scoreInput.nextLine();
scores.add(q);
if (q.equals("q")) {
scores.remove("q");
Student student = new Student(name);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
break;
}
}
}
}
答案 0 :(得分:0)
由于您刚刚学习了这门语言,我会给您一些建议,让您在途中学习。您可能希望使用while
- 循环来一直询问用户新的成绩,直到他们给您一个空行或其他内容。您可以重复使用扫描仪来读取新成绩,并使用Integer.parseInt
将它们转换为整数。希望这能让你进一步编写你的代码,它看起来很棒:)。
修改强>
在您编辑的代码中有几点可以改进。以下显示其中一些(使用import java.io.Console;
):
Scanner inp = new Scanner(System.in);
// Request the name
System.out.print("What is your name? ");
String name = inp.nextLine();
// Create the student object
Student student = new Student(name);
// Ask for the grades
System.out.print("Please enter your scores (q to quit): ");
String grade = inp.nextLine();
while (!grade.equals("q")) {
// Convert the grade to an integer and pass it
student.addQuiz(Integer.parseInt(grade));
// Request a new grade
grade = inp.nextLine();
}
// Report the results
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());