-1

Please forgive me as I am new to all this. My code reads a text file of numbers and names. 3 sets of numbers after each name, each set of 3 gets put into an array. When the array gets sent to another class in the loop, the contents of the array becomes overwritten, I am assuming because it is just referencing the address of the array, not the actual values.

        public void readMarksData(String fileName) throws FileNotFoundException
{
    File dataFile = new File(fileName);
    Scanner scanner = new Scanner(dataFile);

    int[] marks = new int[3];
    scanner.nextLine();

    int i = 0;
    while( scanner.hasNext() )
    {
        String studentName = scanner.nextLine();
        while(i < 3)
        {
            try
            {
                marks[i] = scanner.nextInt();
                i++;
            }
            catch ( InputMismatchException ex )
            {
                i=0;
            }
        }
        scanner.nextLine();
        storeStudentRecord(studentName, marks);
        //scanner.nextLine();
        i=0;
    }
    scanner.close();
}

Code for storing values in another class

    private void storeStudentRecord(String name, int[] marks)
{
    //int[] x = new int[3]
    StudentRecord student = new StudentRecord(name, marks);
    marksList.add(student);
}

Constructor method in other class

    public StudentRecord(String nameInput, int[] marksInput)
{
    // initialise instance variables
    name = nameInput;
    noOfMarks = 0;
    marks = marksInput;
}

This has been driving me nuts for hours so any help would be greatly greatly appreciated, thank you.

vassinator
  • 19
  • 4

1 Answers1

0

You could modify the constructor so that it creates a copy of the array and uses it :

public StudentRecord(String nameInput, int[] marksInput)
{
    // initialise instance variables
    name = nameInput;
    noOfMarks = 0;
    if(marksInput!=null)
     marks = Arrays.copyOf(marksInput, marksInput.length);
    else
     marks = null;
}
boxed__l
  • 1,334
  • 1
  • 10
  • 24