我目前正在开发一个程序,该程序接受班级中学生人数的用户输入,然后(在一段时间循环中)获取学生编号及其平均成绩的用户输入,然后,经过计算,打印班级的最高分、最低分和平均分。
这是我到目前为止所做的:
import java.util.Scanner;
public class ClassMarks {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students in class: ");
int students = input.nextInt();
int x = students;
while (x > 0) {
System.out.println("Enter student number: ");
double studentNumber = input.nextDouble();
System.out.println("Enter student grade: ");
double studentGrade = input.nextDouble();
x = x - 1;
}
}
}
我正在寻找一种方法来让程序为我创建一个新变量,该变量将每个新用户输入的学生成绩存储在 while 循环中。例如)学生一年级,学生二年级,学生三年级...
在while
循环之前,创建最高/最低等级的变量
double highestGrade = Double.MIN_VALUE, lowestGrade = Double.MAX_VALUE;
double gradeSum = 0;
然后,当您遍历值时,适当地调整变量,例如
if (studentGrade > highestGrade)
highestGrade = studentGrade;
if (studentGrade < lowestGrade)
lowestGrade = studentGrade;
gradeSum += studentGrade;
然后在循环结束后,像这样得到平均值
double averageGrade = gradeSum / students;
使用列表怎么样。
List<Student> students = new ArrayList<>()
和在 while 循环中
创建学生 更新其字段,然后将其添加到列表中
Student myNewStudent = new Student();
// update fields
students.add(myNewStudent);
要迭代列表,您可以使用 for 循环。
for (Student s : students) {
// Get student info
}
将其改编到您的代码中:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ClassMarks {
// Create an inner class Student
public static class Student {
public double studentNumber;
public double studentGrade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students in class: ");
int students = input.nextInt();
int x = students;
// Create a list to hold your students
List<Student> studentsList = new ArrayList<>();
while (x > 0) {
Student myNewStudent = new Student();
System.out.println("Enter student number: ");
myNewStudent.studentNumber = input.nextDouble();
System.out.println("Enter student grade: ");
myNewStudent.studentGrade = input.nextDouble();
// update fields
studentsList.add(myNewStudent);
x = x - 1;
}
// Loop your student List
for (Student s : studentsList) {
// Get student info
System.out.println("Student number is: "+s.studentNumber+" grade is : "+s.studentGrade);
}
}
}