跟踪Nullpointerexception背后的原因。但是我该如何解决呢?

时间:2017-04-16 14:23:26

标签: java nullpointerexception

我有一个NullPointerException,我调试了代码并能够跟踪问题,但我该如何解决?

最小测试用例:

    ExecutorService theExecutor = Executors.newFixedThreadPool(10000); //Skapar nya Threads, samt begränsar antalet.
    ServerSocket quizSocket = new ServerSocket(serverPort);

    try {
        while (true) {  //Skriver ut While True
            Socket connection = quizSocket.accept();
            theExecutor.execute(new Broadcaster(connection));
        }
    } finally {
        quizSocket.close();
    }
}

广播班。出现问题的地方:

 public static class Broadcaster extends Thread {

    String quizFile = "src/qa.txt";  // Format of text: Vad heter äventyrets hjälte?/Frodo
    private Socket connection;
    private PrintStream write;
    private String qString;
    private String answer;
    private String question;   // (Debug message) question: null
    int points = 0;

    public Broadcaster(Socket connection) {
        this.connection = connection;
    }

    @Override
    public void run() {
        try {
            write = new PrintStream(connection.getOutputStream());
            //Skriva till klienten.
            List<String> questionsList = new ArrayList<>();

            try (Stream<String> questionsStream = Files.lines(Paths.get(quizFile))) {  //Reading from text file
                questionsList = questionsStream
                        .parallel()
                        .collect(Collectors.toList());
                Collections.shuffle(questionsList);  //Randomizing the Strings.

              while (true) {

    for (String qString : questionsList) {
    String[] questions = qString.split("/");  //Splitting to question[0] and [1]
    write.println(questions[0]);  //Printing out [0]. Has a valid value

    question = questions[1].toLowerCase(); //question = null. question[1] "Sam"

字符串问题仍为空,即使question[1]不是。 NullPointerException是一个事实!这意味着此变量稍后会为getter设置一个空值:

   public void setQuestion(String question) {
   this.question = question;

我想声明一个变量,其值为question[1].toLowerCase而不会导致NullPointerException。然后我想用这个变量生成一个setter。但是我该怎么做?在上一篇文章中,我收到了重复警告,建议您遵循此tutorial。现在我已经做到了,这就是我想出来的。还需要建议如何解决实际问题!我从哪里开始?

有关详细信息,请访问此post

1 个答案:

答案 0 :(得分:-1)

toLowerCase()需要本地化信息,因为大写到小写的转换是特定于语言环境的。无参数toLowerCase()使用默认语言环境的规则转换为小写。当默认语言环境出现问题时,可能会引发NullPointerException

使用显式语言环境参数来解决问题:toLowerCase(Locale.ENGLISH)