I'm having a little trouble with a java array and was hoping for some assistance. I am trying to make a program that will take information from 3 files - one that includes student last names, one that includes their gpa, and one that includes their student number. However, when I run the program I get the afore mentioned ArrayIndexOutOfBoundsException as:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Final.loadArrays(Final.java:40)
at Final.main(Final.java:25)
I have made sure the files contain data and no additional spaces / etc. Please find my code below, and thanks for your assistance.
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.swing.JOptionPane;
public class studentinfo
{
public static void main(String [] args) throws FileNotFoundException
{
final int MAX_SIZE = 3;
String[] names = new String[MAX_SIZE];
double[] gpa = new double[MAX_SIZE];
int[] studentNumber = new int[MAX_SIZE];
loadArrays(names, gpa, studentNumber);
}
public static void loadArrays(String[] names, double[] gpa, int[] studentNumber) throws FileNotFoundException
{
Scanner namesInFile = new Scanner(new FileReader ("names.txt"));
Scanner gpaInFile = new Scanner(new FileReader ("gpa.txt"));
Scanner studentNumberInFile = new Scanner(new FileReader ("studentNumber.txt"));
int i = 0;
//loop for loading names array
while(namesInFile.hasNext())
{
names[i] = namesInFile.next();
i++;
}
i = 0;
//loop for loading gpa array
while (gpaInFile.hasNext())
{
gpa[i] = gpaInFile.nextDouble();
i++;
}
i = 0;
//loop for loading student number array
while (studentNumberInFile.hasNext())
{
studentNumber[i] = studentNumberInFile.nextInt();
i++;
}
namesInFile.close();
gpaInFile.close();
studentNumberInFile.close();
for(i = 0; i < names.length ; i++)
System.out.println(names[i]);
for(i = 0; i < gpa.length ; i++)
System.out.println(gpa[i]);
for(i = 0; i < studentNumber.length ; i++)
System.out.println(studentNumber[i]);
String message = "";
for(i = 0; i < gpa.length ; i++)
message += studentNumber[i]+" "+names[i]+" "+gpa[i]+"\n";
JOptionPane.showMessageDialog(null, message);
}
}