我目前正在制作一个程序,用户输入一个班级中学生的数量,然后(在一个循环中),用户输入一个学号和他们的平均成绩,然后,计算后,打印班级的最高分,最低分和平均分。
这是我到目前为止所做的:
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循环中。 ex)studentGrade1,studentGrade2,studentGrade3 ...
答案 0 :(得分:5)
在(transform [ALL] #(when (not= (key %) :a) %) {:a 1 :b 2})
=> {:b 2}
循环之前,创建变量最高/最低成绩
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;
答案 1 :(得分:0)
如何使用List。
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);
}
}
}