I am trying to have this read the 25 integers from a notepad file (named array.txt) then sort them and output them into another file. When I run it, The output is the 25 integers in the order I have them on notepad (not sorted) along with an exception saying the following:
I have commented in my code where lines 32 and 16 are since that's where the exceptions are happening.
Below is the exception I get.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 25 at writetofile.WriteToFile.processFile(WriteToFile.java:32)
at writetofile.WriteToFile.main(WriteToFile.java:16)
Here is my code:
package writetofile;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class WriteToFile {
public static void main(String[] args) throws IOException {
int[] array=new int [25];
array = processFile ("src/array.txt"); //LINE 16
sortArray(array);
writeToFile ("src/array.txt",array);
}
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
int[] value;
try (BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)))) {
String line;
int i = 0;
value = new int [25];
while ( (line = inputReader.readLine()) != null){
int num = Integer.parseInt (line); // Convert string to
integer.
value[i] = num; //LINE 32
i++;
System.out.println (num); // Test
}
}
return value;
// Read the 25 numbers and return it
}
public static void sortArray (int[] num){ //bubble sort method
boolean order = true;
int temp;
while (order){
order = false;
for (int i = 0; i <num.length-1; i++){
if (num[i]> num[i+1]){
temp = num[i]; //set index to temp
num[i] = num [i+1]; // swap
num[i+1]= temp; //set index to the higher number before it
order = true;
}
}
}
}
public static void writeToFile (String filename, int[] array) throws
IOException{
BufferedWriter outputWriter= new BufferedWriter(new FileWriter(filename));
double number;
for (int counter=0; counter<25; counter ++){
number= array[counter];
String numberString= Double.toString(number);
outputWriter.write(numberString);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
}
processFile()method. think that while condition need a logic to prevent iterations after 25.while ((line = inputReader.readLine()) != null) {you need to add a condition that stops after the 25th line, or use anArrayListinstead.