我试图让用户提交他们的测试分数,然后获得总分和平均分数。我有一个名为student的单独课程,以帮助简化某些任务。
这是学生班:
public class Student {
private String name;
private int numOfQuizzes;
private double totalScore;
public Student(String name){
this.name = name;
}
public String getName() {
return name;
}public void addQuiz(int score){
numOfQuizzes++;
totalScore += score;
}public double getTotalScore() {
return totalScore;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
到目前为止,这是我的主要课程。
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;
}
}
}
}
这是当前的输出。
What is your name? tom
Please enter your scores (q to quit): 13
Please enter your scores (q to quit): 12
Please enter your scores (q to quit): 5
Please enter your scores (q to quit): q
Students Name: tom
Total Quiz Scores: 0.0
Average Quiz Score: NaN
答案 0 :(得分:0)
当你读入你的值时,你需要检查它是字符串还是int,你只想添加整数。您可以执行以下操作:
try{
do{
String q = scoreInput.nextLine();
if(q.equals("q"){
//Do something, like break
break;
}
int numVal = Integer.valueOf(q);
scores.addQuiz(numVal);
} catch (Exception e){
//Handle error of converting string to int
}
}while(true);
//Once you have all the scores, be sure to call your averageScore method
averageScore();
获得分数后,您的平均分数方法应该是:
public double averageScore(){
if(scores != null){
for(int score : scores){
totalScore += score;
}
return totalScore/scores.size();
}
您的学生课程可能如下所示:
public class Student {
private String name;
private int numOfQuizzes;
private double totalScore;
private ArrayList<Integer> scores;
public Student(String name){
this.name = name;
scores = new ArrayList<Integer>();
}
public String getName() {
return name;
}public void addQuiz(int score){
scores.add(score);
}
public double getTotalScore() {
for(int score : scores){
totalScore += score;
}
return totalScore;
}
public double averageScore(){
if(scores != null){
for(int score : scores){
totalScore += score;
}
return totalScore/scores.size();
}
}