1

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();
}

}
4
  • can you share the txt file? Commented Apr 26, 2017 at 0:44
  • suppose the error is in the processFile() method. think that while condition need a logic to prevent iterations after 25. Commented Apr 26, 2017 at 0:46
  • while ((line = inputReader.readLine()) != null) { you need to add a condition that stops after the 25th line, or use an ArrayList instead. Commented Apr 26, 2017 at 0:48
  • I mus have had too many integers in my file. I rewrote 25 new ones and it is functioning properly. Thank you all! Commented Apr 26, 2017 at 1:01

2 Answers 2

2

You are trying to read more than 25 lines - maybe check the file?

Anyway you can prevent this by

 while (i < 25 && (line = inputReader.readLine()) != null){
      // check for blank lines
     if (line.length () < 1) continue;
     int num = Integer.parseInt (line);
     ...
 }
Sign up to request clarification or add additional context in comments.

3 Comments

My guess is that they aren't blank lines due to the integer parsing not throwing an exception
I erased the numbers in my file and wrote 25 new ones to be sure there were only 25 and my problem is fixed so you must have been correct. Thank you!!
java.lang.ArrayIndexOutOfBoundsException says that you are accessing and elements in array which is not holding. It's a runtime exception, to stop you from crashing the system. During such exceptions we normally check the value used to index an array. It is a good practice to check for boundary conditions, that what the above solution do.
0

Using the file array.txt

1
2
32
34
0
34
43
54
43
532
5
43
52
2
43
43
45
5
43
2
54
3
54
324

Using the file WriteToFile.java

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 ("array.txt");   //LINE 16
  sortArray(array);
  writeToFile ("newFile.txt",array);

  }


  public static int[] processFile (String filename) throws IOException, FileNotFoundException{
  System.out.println("Processing File");
  int[] value = new int [25];;
  try {
    BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
    String line;
    int i = 0;
    while ( (line = inputReader.readLine()) != null){
      int num = Integer.parseInt (line);      // Convert string to integer.
      value[i] = num;
      i++;
      System.out.println (num); // Test
    }
  } catch(Exception e) {
    System.out.println(e);
  }
  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 {
    System.out.println("\nWriting to File");
    BufferedWriter outputWriter= new BufferedWriter(new FileWriter(filename));
    double number;
    for (int counter=0; counter<25; counter ++){
      number= array[counter];
      System.out.println(number);
      String numberString= Double.toString(number);
      outputWriter.write(numberString);
      outputWriter.newLine();
    }

    outputWriter.flush();
    outputWriter.close();
  }

}

1 Comment

Whilst this code snippet is welcome, and may provide some help, it would be greatly improved if it included an explanation of how it addresses the question. Without that, your answer has much less educational value - remember that you are answering the question for readers in the future, not just the person asking now! Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.

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.