gpt4 book ai didi

java - 数组不会输出数字总数

转载 作者:太空宇宙 更新时间:2023-11-04 10:29:10 25 4
gpt4 key购买 nike

我试图让用户提交他们的测试成绩,然后获取总分和平均分。我有一个名为 Student 的单独类来帮助简化一些任务。

这是学生类(class):

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;
}
}

这是我迄今为止的主要类(class)。

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

最佳答案

当您读入值时,您需要检查它是字符串还是整数,您只想添加整数。你可能会这样做:

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();
}

您的学生类(class)可能如下所示:

  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();
}
}

关于java - 数组不会输出数字总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50223663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com