I am trying to use the split() method to separate the strings and Integers from an array but cannot get it work.
I get the Index Of Bounds Exception at line 7 where it is says surname = list[1]; and have no idea why?
What I am trying to eventually do is split each element and get the average of the Integers so the first line of text in the file would read Mildred Bush 45 65 45 67 65 and my new line of text that I write to a new file would read Bush, Mildred: Final score is x.xx.
I have tried this for a long while now and can just simply not get it to work.
My code:
public static void splitTest()
{
String forename, surname, tempStr, InputFileName, OutputFileName, nextLine;
int sum = 0;
float average;
//forename = "Mildred";
//surname = "Bush";
nextLine = "";
tempStr = "";
String[] list = tempStr.split(" ");
String[] list = new String[12];
forename = list[0];
surname = list[1];
int[] scores = new int[5];
scores[0] = Integer.parseInt(list[2]);
scores[1] = Integer.parseInt(list[3]);
scores[2] = Integer.parseInt(list[4]);
scores[3] = Integer.parseInt(list[5]);
scores[4] = Integer.parseInt(list[6]);
FileReader fileReader = null;
BufferedReader bufferedReader = null;
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
clrscr();
// Prompt user for input filename
System.out.println("Please enter the name of the file that is to be READ (e.g. details.txt) : ");
InputFileName = Genio.getString();
// Prompt user for output filename
System.out.println("Please enter the name of the file that is to be WRITTEN TO (e.g. newDetails.txt) : ");
OutputFileName = Genio.getString();
try {
// Open input file
fileReader = new FileReader(InputFileName);
bufferedReader = new BufferedReader(fileReader);
// Open output file
outputStream = new FileOutputStream(OutputFileName);
printWriter = new PrintWriter(outputStream);
// Read a line
tempStr = bufferedReader.readLine();
// While there are lines in the input file
while (tempStr != null) {
String[] list;
list = tempStr.split(" ");
surname = list[0];
forename = list[1];
int[] scores = new int[5];
scores[0] = Integer.parseInt(list[2]);
scores[1] = Integer.parseInt(list[3]);
scores[2] = Integer.parseInt(list[4]);
scores[3] = Integer.parseInt(list[5]);
scores[4] = Integer.parseInt(list[6]);
for(int i=0; i < scores.length; i++){
sum = sum + scores[i];
average = (float)sum/scores.length;
// Print it to screen
System.out.println(tempStr);
// Write it to the output file + a new-line
printWriter.write(tempStr +"\n");
// Read a line
tempStr = bufferedReader.readLine();
System.out.println("\n\nYOUR NEW FILE DATA IS DISPLAYED ABOVE!\n\n");
pressKey();
// Close the input file
bufferedReader.close();
// Close the output file
printWriter.close();
}
}
Where it says Genio, this a class that deals with user input. Thank you!