Traced reason behind Nullpointerexception. But how do I solve it? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
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].toLowerCasewithout 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!

toLowerCase() requires localization information because upper-case to lower-case transformation is locale specific. The parameterlesstoLowerCase() converts to lower case using the rules of the default locale. When there is a problem with the default locale a NullPointerException may be raised.
Use an explicit locale parameter to solve the problem: toLowerCase(Locale.ENGLISH)

Related

How do I fix java.lang.ArrayIndexOutOfBoundsException: 2? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I'm writing a program which utilizes OOP. The program I am creating is supposed to recruit applicants to a team. In my Team.java, I created a method which is supposed to accept members and add it to the team. This is a snippet of my code:
public int maxMembers;
public Member members[] = new Member[maxMembers];
public int memberCount = 0;
public void addMember(Member newMember) {
members[maxMembers] = newMember;
memberCount++;
}
I have tried this code but the line,
members[maxMembers] = newMember;
keeps throwing an error java.lang.ArrayOutOfBoundsException: 2
I have tried using a for loop in adding a new member but it does not do what I expected. Can anyone assist me in finding a solution?
You have to assign maxMembers a value in the first line, otherwise your array will have 0 elements.
public int maxMembers = 10;
Firstly, you did not initialize the variable maxMembers.Also, in the code, the line members[maxMembers] = newMember; would always put your entry in the end of the array, I think thats not the intended use of your method, public void addMember(Member newMember)
Rewriting your method would look like,
public int maxMembers=somePositiveInteger;
public Member members[] = new Member[maxMembers];
public int memberCount = 0;
public void addMember(Member newMember) {
members[memberCount] = newMember;//here
memberCount++;
}
Initialize the array with a value so that number of elements in array can be decided.

How to get around array.equals(otherArray) evaluating to null? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to make a for loop that loops through an array, comparing the user input to each object using a method called getID() that returns the stored user IDs for various employees. The data is not saved between runs, so on the first loop, all objects (I believe) should be null. With that being said, I get a nullPointerException on the line that's supposed to compare the strings retrieved by getID() and the userInput string. The array is initialized as follows:
Salesperson[] staffList;
staffList = new Salesperson[20];
Here is the loop in question, the if statement is the line that throws the NPE:
for(i = 0; i < staffList.length; i++)
{
if(staffList[i].getID().equals(idNum))
{
duplicateID = true;
}
}
Here is the class for the Salesperson array:
public class Salesperson
{
private String name;
private String idNum;
private double annSales;
//Various getter and setter methods here
}
If I missed anything please let me know. I've used Stack Overflow in the past but have never asked a question myself. I've tried searching around here but have yet to find anything that helped me. Thanks in advance!
You can update your code something like below to avoid NPE.
Salesperson[] staffList;
staffList = new Salesperson[20];
for(int i = 0; i < staffList.length; i++)
{
Salesperson salesPerson = staffList[i]; // staffList[i] i.e salesPerson = null.... null.getId throws NPE.
System.out.println("sales =" + sales); // sales = null
if(sales != null) {
if (sales.getId().equals(idNum)) {
//Do something..
}
}
}

Exception in thread "Thread-4" java.lang.NullPointerException in call the constructor [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am building a midi piano in java. In this case, I want to play pitches ,record pitches and playback them.
Then I used java thread to add pitch to queue and add delay to queue. I used thread object to these process and call it in constructor. After the call this constructor it gives NullPointException.
Can you help me found out why?
public PianoPlayer() throws MidiUnavailableException{
queue = new LinkedBlockingQueue<NoteEvent>();
delayQueue = new LinkedBlockingQueue<NoteEvent>();
machine = new PianoMachine(this);
processQueue.start();
processDelayQueue.start();
}
Thread processDelayQueue = new Thread() {
public void run(){
while(true){
if(queue.isEmpty()){
}
else{
try {
NoteEvent e=queue.take();
midi.Midi.wait(100);
queue.put(e);
} catch (InterruptedException ex) {
Logger.getLogger(PianoPlayer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
};
Check if processQueue and processDelayQueue are not null. NullPointerException is usually caused when you try to call a method or get a value from a variable in an object that is null.
Such as
MyClass c = null;
// NullPointerException
String name = c.getName();
Possible Fix
MyClass c = null;
if (c == null) {
// initialize
c = new MyClass();
}
// This will work
String r = c.getName();
You need to always have a null check because it is very common to get a null variable.

Referencing between class Object initialized with null [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 5 years ago.
Here is my example: I want to know if it is possible to pass an argument initialized with null, and later initialize the object with a correct value.
private class Source {
String str;
String getStringValue() {
return str;
}
void setStringValue(String str) {
this.str = str;
}
}
private class UserSource {
Source src;
UserSource(Source src) {
this.src = src;
}
String getValue() {
return src.getStringValue();
}
void setValue(String str) {
src.setStringValue(str);
}
}
Now how I'm using.
Source srcW = new Source();
UserSource userSourceW = new UserSource(srcW);
srcW.setStringValue("Second Value");
System.out.println("From UserSource:" + userSourceW.getValue());
userSourceW.setValue("Is not Second");
System.out.println("From Source:" + srcW.getStringValue());
The output:
From UserSource:Second Value
From Source:Is not Second
But, want to know if is possible to use like:
Source srcN = null; // YES I want to assign Not initialized!
UserSource userSourceN = new UserSource(srcN);
srcN = new Source();
srcN.setStringValue("First Value");
System.out.println("From UserSource:" + userSourceN.getValue());
Of course the output is
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
Is there an alternative?
Unfortunately, it's not possible to do so. When the value is initially null, then you're passing the null reference. Later you initialize it with srcN = new Source();, but then you're rewriting the source.
You could work around it with a Reference<Source>. But that would only make the code more cumbersome. Moreover, the Source class is a perfect candidate to pass it as an empty source, and then initialize it later with setString().
Am I missing something? What's your problem with the code as is?

Returning the reverse of a string using recursion? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to return the reverse of a string using recursion but I got a few errors. I'm new to recursion so I don't really know where to start. The errors I'm getting are:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.concat(String.java:2027)
at Recursion.reverseString(Recursion.java:30)
at Recursion.reverseString(Recursion.java:30)
at Recursion.reverseString(Recursion.java:30)
at Recursion.reverseString(Recursion.java:30)
at Recursion.reverseString(Recursion.java:30)
at Recursion.main(Recursion.java:46)
Here's my code:
public static String reverseString (String inString) {
String result = "";
if (inString.length() > 0) {
// if the string is empty
result = inString.charAt(inString.length()-1) + "";
result.concat(reverseString(inString.substring(0, inString.length()-1)));
return result;
} else {
return null;
}
}
// the testers
public static void main(String[] args){
String inString = "abcde";
// test the reverseString
String revString = reverseString(inString);
System.out.println(revString);
}
}
The exception stacktrace is telling you that null is being passed to the concat() method. The argument to concat() is your reverseString() method which returns null when the string is empty. Instead of returning null, you could return an empty String to avoid the NullPointerException. Replace the line:
return null;
with
return "";
In addition to what #Asaph said you also need to assign this expression
result.concat(reverseString(inString.substring(0, inString.length()-1)));
to your result variable so that it becomes:
result = result.concat(reverseString(inString.substring(0, inString.length()-1)));
Otherwise it won't work because the concat method of the String class does not return the same object from which it was called

Categories

Resources