从arraylist访问对象

时间:2018-01-17 06:01:28

标签: java object arraylist

我正在尝试制作这个为人们创建队列的程序,我的问题是我似乎无法以任何方式从主类中访问其中一个对象值...任何帮助将不胜感激,我不喜欢#39;我认为我对这些互相访问的具体程度有很深的了解。

这是我的代码(我试图访问代码时有//注释块)

    import java.util.*;
class Student{
    private int age;
    private String fname;
    private double grade;
    public Student(String fname, int age, double grade) {
        super();
        this.age = age;
        this.fname = fname;
        this.grade = grade;
    }
    public int getAge() {
        return age;
    }
    public String getFname() {
        return fname;
    }
    public double getGrade() {
        return grade;
    }
}


public class javasort
{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        List<Student> studentList = new ArrayList<Student>();
        int end = 0;
        while(end==0){
            String line = in.nextLine();
            if (line.equalsIgnoreCase("end")) {
                end++;
                break;
            }
            String[] studentValues = line.split(" ");
            int[] values = new int[2];
            String fname = studentValues[0];
            for(int i = fname.length(); i < studentValues.length-1; i++){
                values[i] = Integer.parseInt(studentValues[i]);
            }
            int age = values[0];
            double grade = values[1];
            Student st = new Student(fname, age, grade);
            studentList.add(st);

            // This line wont access anything, I want to be able to get the age of the 2nd last person in line
            // and then compare it to the last person in line. although I cannot seem to be able to "get" the age of the 2nd last.
            Student second = (studentList).getAge(studentList.size()-2);
        }




        for(Student st: studentList){
            System.out.println(st.getFname());
        }
    }
}

2 个答案:

答案 0 :(得分:0)

使用此

studentList.get(studentList.size()-2).getAge();

如果列表的大小为1会发生什么,它将返回异常

线程中的异常&#34; main&#34; java.lang.ArrayIndexOutOfBoundsException:-1

答案 1 :(得分:0)

jj mackubin,

注意到两点:
1. for循环逻辑错误。使用i = fname.length()初始化循环,只需输入带有5个字母的名称,然后以5开头循环,而不是从1开始。 根据您的代码,初始化条件应为i = 1,该代码在第0个索引处读取名称 2.使用@Prabhakar Kumar建议的get(int index)函数来获取Student对象,然后获取该类的相应属性。