I am trying to filter out specific elements of my array list but I keep getting an undeclared variable error.
public class Student
{
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGpa)
{
name = studentName;
age = studentAge;
gpa = studentGpa;
}
public String toString()
{
return "Student[Name: " + name + " Age: " + age + " GPA: " + gpa + "]n";
}
}
The Students class is supposed to set up the array list and have multiple methods to determine which student has the highest GPA, the average GPA, etc…
import java.util.ArrayList;
import java.util.*;
import java.text.*;
import java.io.*;
public class Students
{
private ArrayList<Student> students;
public Students()
{
students = new ArrayList<Student>();
}
public void readFile() throws IOException
{
String studentName;
int studentAge;
double studentGpa;
String line;
Scanner sc = new Scanner(new File("Students.txt"));
while (sc.hasNextLine())
{
studentName = sc.nextLine();
line = sc.nextLine();
studentAge = Integer.parseInt(line);
line = sc.nextLine();
studentGpa = Double.parseDouble(line);
Student student = new Student(studentName, studentAge, studentGpa);
students.add(student);
}
sc.close();
}
public String toString()
{
String results = "Students [";
for(int i = 0; i < students.size(); i++)
{results += students.get(i).toString(); }
return results;
}
//this method keeps saying studentGpa is an undeclared variable
public double highestGpa()
{
double highestGpa = students.get(0).studentGpa;
for(int i = 0; i < students.size(); i++)
if( students.get(i).studentGpa > highestGpa)
highestGpa = students.get(i).studentGpa;
}
}
The trouble I’m having is in the highestGpa() method. I am trying to access the studentGpa element inside of the array list but it keeps saying studentGpa is an undeclared method.
I tried changing studentGpa to gpa since I decided to create the Student constructor without using the ‘this’ keyword but since it was a private variable it wont work.
How should I go about accessing these different elements in the array list inside of separate methods?
Jourdie Browne is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.