对象数组测试但没有得到任何输出

时间:2017-05-25 19:04:21

标签: java arrays class object

我想对我正在测试的这个特定代码提供一些指导,但目前它没有打印出任何内容,而且我觉得好像根本没有读取文本文件。它似乎立即完成没有错误,我只得到“构建成功”的提示。 作业是从数据文本文件中读取,该文件列出20行学生信息,每行由名字,姓氏和等级组成,全部由空格分隔。我把它放到一个数组并输出他们的信息,但是现在我正在测试它是否会在我继续之前输出名字。

public class studentClass {
private String studentFName, studentLName;
private int testScore;
private char grade;

//constructor
public studentClass(String stuFName, String stuLName, int stuTestScore){
    studentFName = stuFName;
    studentLName = stuLName;
    testScore = stuTestScore;
}

public String getStudentFName(){
    return studentFName;
}

public String getStudentLName(){
    return studentLName;
}

public int getTestScore(){
    return testScore;
}

public char getGrade(){
    return grade;
}

public void setStudentFName(String f){
    studentFName = f;
}

public void setStudentLName(String l){
    studentLName = l;
}

public void setTestScore(int t){
    if (t>=0 && t<=100){
    testScore = t;
    }
}

public void setGrade(char g){
    grade = g;
}
}
public static void main(String[] args) throws IOException {

    int numberOfLines = 20; 
    studentClass[] studentObject = new studentClass[numberOfLines];

    for(int i = 0; i>studentObject.length; i++){
        System.out.print(studentObject[i].getStudentFName());
    }

}
public static studentClass[] readStudentData(studentClass[] studentObject)throws IOException{
    //create FileReader and BufferedReader to read and store data
    FileReader fr = new FileReader("/Volumes/PERS/Data.txt");
    BufferedReader br = new BufferedReader (fr);

    String lines = null;
    int i = 0;

    //create array to store data for firstname, lastname, and score
    while ((lines = br.readLine()) != null){
       String stuArray[] = lines.split(" ");
       String stuFName = stuArray[0];
       String stuLName = stuArray[1];
       int score = Integer.parseInt(stuArray[2]);
       studentObject[i] = new studentClass (stuFName, stuLName, score);
       i++;
    }

    return studentObject;
}

1 个答案:

答案 0 :(得分:1)

您需要实际调用该方法来读入数据。尝试以下(注意我没有处理异常。我把它作为练习留给你)

public static void main(String[] args) throws IOException {
    int numberOfLines = 20; 
    studentClass[] studentObject = new studentClass[numberOfLines];
    readStudentData(studentObject);

    //NOTE I CHANGED THE '>' TO '<'
    for(int i = 0; i < studentObject.length; i++){
        System.out.print(studentObject[i].getStudentFName());
    }
}

//Note that I changed the return type to void
public static void readStudentData(studentClass[] studentObject)throws IOException{
    //Your code here

您会看到我更改了您的readStudentData以返回void,因为您已将数组传递给您不需要返回的方法。您需要删除其末尾的return

您也可以将其保留为返回studentClass []并且没有参数的方法。而是在readStudentData中创建studentClass数组。我建议使用这种方法,因为它不需要创建和传递数组,这会使你的main方法复杂化。