NULL指针异常故障

时间:2013-05-07 23:36:12

标签: java nullpointerexception

所以我正在制作 PigLatin转换器,我有一些NullPointerException。现在你可能会问我是不是自己尝试了它而且我对你的回答是肯定的。无论如何这里是我的代码:导致错误的行将以“错误”结束

package project.pkg16.pkg9;

public class Project169_Data {

private static String[] words;
private static String pigLatinWords;

public static void setWords( String input ) {
    words = input.split(" ");
}

public static String convertToPigLatin() {
    for (int i = 0; i < words.length; i++) {
        String wordTemp = null;
        String word = words[i].toString();
            char firstLetter = word.charAt(0);
            StringBuilder sb = new StringBuilder(word.toString());
            sb.append( String.valueOf(firstLetter).toLowerCase() );
            sb.deleteCharAt(0);
            sb.append("ay ");
            StringBuilder sb2 = new StringBuilder(wordTemp);   LINE 24 ERROR
            sb2.append(sb.toString());
            pigLatinWords = sb2.toString();
            }
       return pigLatinWords;
    }
}

然后这是第二课:

package project.pkg16.pkg9;

public class Project169_Main {

public static Project169_Input project169_Input = new Project169_Input();
public static Project169_Data project169_Data = new Project169_Data();

public static void main(String[] args) {
    String userInput = Project169_Input.getInput();

    project169_Data.setWords(userInput);

    String pigLatinString = project169_Data.convertToPigLatin();       LINE 14 ERROR

 }
}

最后是第3课:

package project.pkg16.pkg9;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Project169_Input {

public static String getInput() {

JFrame frame = new JFrame("English to Pig Latin");
String input = JOptionPane.showInputDialog(frame, "Enter the english words you wish to convert to Pig Latin.");

return input;
} //End of method...
} //End of Class...

错误是:

运行:

    Exception in thread "main" java.lang.NullPointerException
at java.lang.StringBuilder.<init>(StringBuilder.java:92)
at project.pkg16.pkg9.Project169_Data.convertToPigLatin(Project169_Data.java:24)
at project.pkg16.pkg9.Project169_Main.main(Project169_Main.java:14)
    BUILD SUCCESSFUL (total time: 31 seconds)

1 个答案:

答案 0 :(得分:5)

wordTemp为null且永远不会更改。您正在尝试使用null变量创建StringBuilder。

解决方案:不要这样做。

顺便说一下:下次请注明哪条线正在抛出NPE。即使在您编辑之后,您还没有仍然。请不要强迫我们一次计算一行代码。类似的东西:

StringBuilder sb2 = new StringBuilder(wordTemp);  // **** this line throws NPE
sb2.append(sb.toString());
pigLatinWords = sb2.toString();

另外,

  • 您需要修复代码格式,尤其是目前存在错误的缩进,这使您和我们难以调试。
  • 我认为你真的想要创建没有参数的StringBuilder,而之前创建for循环。
  • 我认为您希望在 for循环之后在StringBuilder 上调用toString()