0

Why isn't this code working? Could you please give me some help?

  • I want to read 60 lines of words from the file,like"smell,", print all the values in the order, sorts the values, and prints the values again.
  • I use compareTo as the selection sort algorithm for the String type. However, when I run the code, it shows as follow: " Exception in thread "main" java.lang.NullPointerException at practice.selectionSort(practice.java:36) at practice.main(practice.java:10)"

So what the problems of this code are? Thank you!!

import java.util.Scanner;
import java.io.*;
public class practice
{
   public static void main (String[] args) throws IOException
   {
      final int DATA_NUM = 60; 
      String[] array = new String[DATA_NUM];
      readData(array);
      selectionSort(array);
      printData(array);

   }

   public static String[] readData(String[] array) throws IOException 
   {
      String filename = "input.txt";
      Scanner file = new Scanner(new File(filename));
      int count = 0;
      while(file.hasNext())
      {
         String newLine = file.nextLine();
         array[count] = newLine;
         count++;
      }
      for(int i = 0; i < array.length; i++)
      {
         System.out.println(array[i]);
      }
      return array;
   }

   public static String[] selectionSort(String[] array)
   {
      for(int x = 1; x < array.length; x++)
      {
         int s = x - 1;
         for(int y = x; y < array.length; y++)
         {
            if(array[y].compareTo(array[s]) < 0)
            {
               s = y;            
            }
         }
         String minValue = array[x-1];
         array[x-1] = array[s];
         array[s] = minValue;
      }
      return array;
   }
   public static String[] printData(String[] array)
   {
      for(int i = 0; i < array.length; i++)
      {
         System.out.println(array[i]);
      }
      return array;
   }
}
Erica
  • 1
  • 1
    Some general long term advice: Learn how to use a debugger. Doing so would give you a wealth of information about what is happening with your code. – Tim Biegeleisen Jul 11 '17 at 07:30
  • The linked Q&A includes lots of useful stuff about common causes of NPEs, and an explanation of how to diagnose an NPE from the stacktrace. – Stephen C Jul 11 '17 at 08:05

0 Answers0