-1

I'm programming a code that writes an array of integers to a file. However, it keeps giving me a NullPointerException. Which I think is in one of two methods that I have, I know it's somewhere in there, but I can't spot it. Here's the code.

public static void WriteToFile (int[] n)throws IOException{
    try{
        BufferedWriter bw=new BufferedWriter(new FileWriter("C:\\sortfile2.txt"));
        for(int i=0;i<=25;i++){
            bw.write(sortArray(n)+" ");
        }
        bw.flush();
        bw.close();
    }
    catch(IOException e){
        System.out.println("Could not write to file");
    }
}

This is the first method that the error could be located in. The second is here:

public static int sortArray(int[] a){
    int sort=0;
    for(int i=0;i<a.length;i++){
        int max=IndexOfMaxInRange(a,i,a.length-1);
        sort=SwapElement(a,max,max++);
        a[i]=sort;
    }
    return sort;
}

Where IndexOfMaxInRange is a method that finds the highest integer of an array, and where SwapElement is a method that implements IndexOfMaxInRange, and swaps the highest number in the array, with the lowest.

Mohammad Ashfaq
  • 1,333
  • 2
  • 14
  • 38
theUser
  • 91
  • 5

2 Answers2

0

Try this code,and edit according to yours(this works for me)...

 public static void write (String filename, int[]x) throws IOException{
      BufferedWriter outputWriter = null;
      outputWriter = new BufferedWriter(new FileWriter(filename));
      for (int i = 0; i < x.length; i++) {
        // Maybe:
        outputWriter.write(x[i]+"");
        // Or:
        outputWriter.write(Integer.toString(x[i]);
        outputWriter.newLine();
      }
      outputWriter.flush();  
      outputWriter.close();  
    }
Miller
  • 744
  • 3
  • 15
  • 39
  • Any reason why not simply do `BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));`? I didn't follow your `make sure your buffered writer was declared as null`... – Luan Nico Apr 28 '15 at 12:51
0

Your custom sort doesn't work and will be causing the issue. In particular

for(int i=0;i<a.length;i++)

means i becomes the last element of the array

so

    int max=IndexOfMaxInRange(a,i,a.length-1);
    sort=SwapElement(a,max,max++);

has some rather worrying index bounds issues around max, and max++ seems to be pointless.

Try it without the sorting to pinpoint your issue.

Ashley Frieze
  • 4,993
  • 2
  • 29
  • 23