2013-09-24 25 views
-2

该程序读取输入文件的行并将它们存储到数组字中。然后将[]中的每个元素放入一个字符数组中并按字母顺序排序。每个排序的字符数组都被分配给一个字符串,并且这些字符串填充另一个数组sortedWords。我需要排序sortedWords数组中的元素。当我使用Arrays.sort(sortedWords)时,我得到一个NullPointerException异常。使用java.util.Arrays.sort的NullPointerException()

public static void main(String[] args) throws FileNotFoundException { 
    Scanner scanner = new Scanner(System.in); 
    System.out.print("Enter a file name: "); 
    System.out.flush(); 

    String filename = scanner.nextLine(); 
    File file = new File(filename); 

    String[] words = new String[10]; 
    String[] sortedWords = new String[10]; 

    try { 
     FileReader fr = new FileReader(file); 
     BufferedReader br = new BufferedReader(fr); 

     String line = br.readLine(); 
     int i = 0; 

     while(line != null) { 
      words[i] = line.toString(); // assigns lines into the array 
      line = br.readLine(); // this will eventually set line to null, terminating the loop 

      String signature = words[i];       
      char[] characters = signature.toCharArray();   
      Arrays.sort(characters); 
      String sorted = new String(characters);    

      sortedWords[i] = sorted; // assigns each signature into the array 
      sortedWords[i] = sortedWords[i].replaceAll("[^a-zA-Z]", "").toLowerCase(); // removes non-alphabetic chars and makes lowercase 
      Arrays.sort(sortedWords); 

      System.out.println(words[i] + " " + sortedWords[i]); 
      i++; 
     }  
    } 

    catch(IOException e) { 
     System.out.println(e); 
    } 
} 
+0

希望你的文件只有10行。 –

+0

@SotiriosDelimanolis yep – dk1

回答

2

你应该花sortwhile循环。

int i = 0; 
while(line != null) { 
    ... 
    i++; 
} 
Arrays.sort(sortedWords, 0, i); 

的问题是,你叫sort你完成填充sortedWords阵列之前。因此阵列仍然包含null字符串,并且这些会导致NullPointerException

+0

依然给我一个'NullPointerException' – dk1

+0

输入文件也需要有10行才能工作。如果超过10个数组索引将超出范围,并且如果少于10个,则会出现相同的空指针异常 – GregA100k

+0

您的文件可能没有10行。考虑使用'列表'和'Collections.sort' – cyon

相关问题