3

I am having a problem in this code. what i am trying to do is read a file and store a studentID and score into an array of scores into the scores property of a student object, but I keep getting the last scores only when I print. Here is the code. can you tell me if my setter property is a correct way of assigning an array in the student class? the problem is the last line of the score file is stored in every array even though when I debug it I see the score array being passed and the studentID array works fine.

import lab6.*;//importing the necessary classes

public class Main 
{
    public static void main(String[] args) 
    {
        Student lab6 [] = new Student[40];
        //Populate the student array
        lab6 = Util.readFile("studentScores.txt", lab6);    
        lab6[4].printStudent();         
    }

}

The student class------------------------------------

package lab6;

public class Student 
{
    private int SID;
    private int scores[] = new int[5];
      //write public get and set methods for SID and scores
    public int getSID()
    {
        return SID;
    }

    public void setSID(int SID)
    {
        this.SID = SID;
    }
    public int[] getScores()
    {
        return scores;
    }

    public void setScores(int scores[])
    {
        this.scores = scores;
    }
    //add methods to print values of instance variables.
     public void printStudent()
     { 
         System.out.print(SID);
         System.out.printf("\t");
         for(int i = 0; i < scores.length; i++)
         {
             System.out.printf("%d\t", scores[i]);
         }
     }
}


the util class --------------------------------------------------------------------

import java.io.*;
import java.util.StringTokenizer;

//Reads the file and builds student array.
//Open the file using FileReader Object.
//In a loop read a line using readLine method.
//Tokenize each line using StringTokenizer Object
//Each token is converted from String to Integer using parseInt method
//Value is then saved in the right property of Student Object.
public class Util 
{
    public static Student [] readFile(String filename, Student [] stu)
    {
        try {
            String line[] = new String[40];//one line of the file to be stored in here
            StringTokenizer stringToken;
            int studentID;//for storing the student id
            int[] studentScoreArray = new int[5];//for storing the student score

            FileReader file = new FileReader(filename);
            BufferedReader buff = new BufferedReader(file);

            boolean eof = false;
            int i = 0;
            buff.readLine();//used this to skip the first line
            while (!eof) //operation of one line
            { 
                line[i] = buff.readLine();
                if (line[i] == null)
                    eof = true;
                else //tokenize and store
                {
                    stringToken = new StringTokenizer(line[i]);
                    String tokenID = stringToken.nextToken().toString();//for storing the student id
                    studentID = Integer.parseInt(tokenID);
                    stu[i] = new Student();//creating student objects
                    stu[i].setSID(studentID);//stored in student object
                    //now storing the score-------------------------------------------------
                    int quizNumberCounter = 0;
                    while (stringToken.hasMoreTokens()) 
                    {
                        String tokens = stringToken.nextToken().toString();
                        studentScoreArray[quizNumberCounter] = Integer.parseInt(tokens);//converting and storing the scores in an array
                        quizNumberCounter++;//array progression

                    }
                    stu[i].setScores(studentScoreArray);//setting the score(passing it as an array)
                    //-----------------------------------------------------------------------

                }
                i++;

            }
            buff.close();
        } catch (IOException e) {
            System.out.println("Error -- " + e.toString());
        }

        return stu;
    }
/*
     StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         System.out.println(st.nextToken());
     }
//How to convert a String to an Integer
    int x = Integer.parseInt(String) ;*/
}

Sample file Structure -------------------------------------------------------

4532 011 017 081 032 077 
2
  • try using while((buff.readLine()) != null) for reading each line from the file and you will not need to use of that boolean eof Commented Jun 3, 2011 at 4:56
  • thanks for the tip but can you check if i am passing the array correctly or not Commented Jun 3, 2011 at 5:03

3 Answers 3

2

The issue lies within the line

int[] studentScoreArray = new int[5];

You'll have to move this one inside your student loop and initialize the array per student. Otherwise you are reusing the same array (i.e. memory) for all students and you are overwriting scores over and over again.

// int[] studentScoreArray = new int[5]; // <= line removed here!!!

...

while (!eof) //operation of one line
{ 
    line[i] = buff.readLine();
    if (line[i] == null)
        eof = true;
    else //tokenize and store
    {
        int[] studentScoreArray = new int[5]; // <= line moved over to here!!!

        ...
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

how do I do that? they are in a separate class, I suspected the same thing but I am passing an array to be assigned to studentScoreArray
@dave there is this checkbox left to the answer - just click it (see also FAQ)
0

I havent tested the code with my suggestion, but take a look at:

int[] studentScoreArray = new int[5];

You create this once and once only for the whole file. A simple and easy fix is to do it for every new line read instead.

like this :

int[] studentScoreArray = new int[5];
int quizNumberCounter = 0;
while(..) { ...}

2 Comments

the problem is I am passing an array to a setter method I dont know how to do it without moving that code inside a loop. I want to do it with just passing an array.
well, the problem right now is that you are using the same array over and over again to store all student scores (i.e you overwrite it everytime). That's why you need to put in a initialize a new array everytime you read student scores.
0

One reason you may only being seeing one line of results is that you are only printing one line of results:

lab6[4].printStudent();

You will need to change this to loop through the array if you want to see all the results:

foreach (Student student : lab6)
{
    student.printStudent();
}

On a side note, your array should probably be called something like students instead of lab6. Also it is idiomatic in java to declare arrays using Type[] identifier rather than Type identifier [].

DISCLAIMER: There may be other stuff wrong, I didn't read all the hundreds of lines posted!

1 Comment

the problem is the last line of the score file is stored in every array even though when I debug it I see the score array being passed and the studentID array works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.