-1

我必须编写一个程序,要求用户输入 10 个名称,然后按字母顺序对名称进行排序,然后打印每个名称、多少个字符和多少个元音。我想我很接近但在处理过程中不断收到这个错误。有人能帮忙吗?

`Exception in thread "Animation Thread" java.lang.NullPointerException
at java.lang.String$CaseInsensitiveComparator.compare(String.java:1217)
at java.lang.String$CaseInsensitiveComparator.compare(String.java:1211)
at java.lang.String.compareToIgnoreCase(String.java:1258)
at test.setup(test.java:35)
at processing.core.PApplet.handleDraw(PApplet.java:2117)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:193)
at processing.core.PApplet.run(PApplet.java:2020)
at java.lang.Thread.run(Thread.java:662)`

我的代码是:

import javax.swing.*;
String names[] = new String[10];
String temp;
String nameInput;
int length;
int vowel = 0;
char ch;
length = 0;
// store user input to array
for (int i = 0; i < names.length; i++) {
  nameInput = JOptionPane.showInputDialog ("Enter a name:");
  names[i] = nameInput;
  length = names[i].length();

// sort into alphabetical order
  for (int j = 0; j < names.length - 1; j++) {
    for (int k = j + 1; k < names.length; k++) {
      if (names[j].compareToIgnoreCase(names[k]) > 0) {
        temp = names[j];
        names[j] = names[k];
        names[k] = temp;
      }
    }
  }
  // count vowels
  char[] characters = nameInput.toCharArray();
  for (int m = 0; m < characters.length; m++) {
    ch = nameInput.charAt(m);

    if ((ch == 'A') || (ch == 'a')
      ||  (ch == 'E') || (ch == 'e')
      ||  (ch == 'I') || (ch == 'i')
      ||  (ch == 'O') || (ch == 'o')
      ||  (ch == 'U') || (ch == 'u')) {
      vowel++;
    }
  }

  System.out.println("Name: " + names[i] + ", Length: " + length + ", Vowels: " + vowel);
  vowel = 0;
}
4

2 回答 2

3

这就是问题:

for (int i = 0; i < names.length; i++) {
  nameInput = JOptionPane.showInputDialog ("Enter a name:");
  names[i] = nameInput;
  length = names[i].length();

  // sort into alphabetical order
  for (int j = 0; j < names.length - 1; j++) {
    for (int k = j + 1; k < names.length; k++) {
      if (names[j].compareToIgnoreCase(names[k]) > 0) {

您正在尝试在输入 names 的同一循环中进行排序。

所以在输入名字后,第一个元素将是非空的,但所有其他数组元素都是空引用,这就是导致问题的原因。

我建议你把它分成两个单独的循环:

  1. 输入所有名称
  2. 对它们进行排序

基本上,您需要提前关闭第一个循环:

for (int i = 0; i < names.length; i++) {
  // No need to use a separate variable: assign directly into the array
  names[i] = JOptionPane.showInputDialog ("Enter a name:");
}
于 2013-02-06T15:06:27.640 回答
-2

您的字符串数组的语法也是错误的。

String names[] = new String[10];

正确的方法是:

String[] names = new String[10];
于 2013-02-06T15:16:42.533 回答