1

该程序读取输入文件的行并将它们存储到数组单词中。然后将 words[] 中的每个元素放入字符数组并按字母顺序排序。每个排序的字符数组都分配给一个字符串,这些字符串填充另一个数组 sortedWords。我需要对 sortedWords 数组中的元素进行排序。使用 Arrays.sort(sortedWords) 时出现 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);
    }
}
4

1 回答 1

3

你应该sort跳出while循环。

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

问题是您sort在完成填充sortedWords数组之前调用。因此,该数组仍然包含null字符串,这些会导致NullPointerException.

于 2013-09-24T17:33:56.303 回答