Reputation: 43
I've been searching every where but couldn't find an answer.
I'm trying to make an ArrayList to store 10 grades in a user defined class so I can then call it in the Client class and input the grades with a Scanner(System.in) and then output them all together but I don't know if its possible to do it and I've searched everywhere for an answer. Please Help.
This is what I have so far of my user defined class
import java.util.ArrayList;
public class Student {
private String student;
private String courseName;
private double grade;
private double avg;
private double total;
private double max;
private double min;
//Constructor w/o arguments
public Student() {
this.student = "";
this.courseName = "";
this.grade = 0.0;
}
//Constructor with arguments
public Student(String student, String courseName, double grade, double avg, double total, double max, double min) {
this.student = student;
this.courseName = courseName;
this.grade = grade;
}
//Getters
public String getStudent(){
return this.student;
}
public String getCourseName() {
return this.courseName;
}
//Setters
public void setStudent(String student) {
this.student = student;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
//Returns average off the 10 grades
public double calculateAvg() {
total += grade; //add all grades for average
avg = total / 10;
return avg;
}
//Highest Grade
public double highGrade() {
return max = Math.max(grade, max);
}
//Lowest Grade
public double lowGrade() {
return min = Math.min(grade, min);
}
ArrayList<Student>listGrades = new ArrayList<Student>();
Upvotes: 0
Views: 2638
Reputation: 296
You should try something like this.
public static void main(String[] args) {
System.out.println("Enter number of Students :");
Scanner scanner = new Scanner(System.in);
Student s=new Student("gagan","Math",0.0d,0.0d, 0.0d, 0.0d,0.0d);
s.listGrades.add(s);
for(Student s1:s.listGrades) {
System.out.println("Enter Grade for student"+s.getStudent()+": ");
s1.setGrade(scanner.nextDouble());
}
scanner.close();
}
Upvotes: 0
Reputation: 2907
Initialize it in a constructor or another method: [https://www.geeksforgeeks.org/initialize-an-arraylist-in-java/][1]
Upvotes: 0
Reputation: 2347
Not sure to understand what you want but that will do it :
class Student {
private final List<Double> grades = new ArrayList<>(10);
private final String name;
// Constructor, getters & setters omitted.
}
// ..
Student student = // ...
for (int i=0; i<10; i++) {
System.out.println("Please enter the "+(i+1)+"th grade:");
student.getGrades().add(scanner.nextDouble());
}
// ..
Student student = // ...
student.getGrades().forEach(System.out::println);
Note that is not the optimal way to do it. You can search the https://codereview.stackexchange.com/ community for "student grade java" to find a lot of review on similar questions.
Upvotes: 2