I have a NullPointerException, I have debugged the code and was able to trace the problem but how do I solve it?
Minimal test case:
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();
}
}
Broadcaster class. where the problem occurs:
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"
The string question is still null, even though question[1]
is not. The NullPointerException is a fact! Which means that this variable sets a null value to the getter later on:
public void setQuestion(String question) {
this.question = question;
I want to declare a variable, with the value of question[1].toLowerCase
without causing a NullPointerException. Then I want to generate a setter with this variable. But how do I do this? In a previous post, I received a duplicate warning and was suggested to follow this tutorial. Now I have done that, and this is what I came up with. Still need advice how to solve the actual problem! Where do I go from here?
For more information, visit this post!