我正在研究一个代码,你有一个学生的名字和他的成绩,它打印了他的名字总分和他的平均分。我想让它更实用,允许用户在那里输入名称和分数并获取所有这些信息。我可能会尝试将其进一步转换为班级平均值,其中允许输入多个个人姓名、分数和平均值,分别打印每个名称,然后显示班级平均值。不过,这是第二个想法,因为我需要首先让用户输入等级和名称。
这就是我目前所拥有的。 我有一个单独的类来简化一些事情。
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;
}
}
}
}
由于您还只是在学习语言,因此我会给您一些建议,以送您上路。您可能希望使用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());