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..
}
}
}
Related
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.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
Looking for some help here. I'm trying to make this method work. Whenever I run the method, it throws IllegalArgumentException even if I do type in A,B,C or D. I am using an inputReader class. Here is the code for my DriverExam class. Please let me know where I am going wrong. I'd like it so the only valid answers are a,b,c,or d. I have to use a while loop and everything I've tried won't help me match the driverAnswers.
public class DriverExam
{
// instance variables
public static final String[] ANSWERS = {"B","D","A","A","C","A","B","A","C","D","B","C","D","A","D","C","C","B","D","A"};
private String [] driverAnswers;
private InputReader inputReader;
public DriverExam(){
driverAnswers = new String[20];
inputReader = new InputReader();
}
public void promptStudentAnswers(){
int index = 0;
while(index < driverAnswers.length){
System.out.println("enter answer");
String driverAnswers = inputReader.readString();
if(driverAnswers != ANSWERS[index]){
throw new IllegalArgumentException(" answers can only be A,B,C or D");
} else{
index++;
}
}
}
}
First, you want to test if the answer is one of A, B, C or D (not that the answer matches something in the correct answers array). Also, your driverAnswers is masked because you created another local variable with that name. Basically, I think you wanted something like
public void promptStudentAnswers() {
int index = 0;
while (index < driverAnswers.length) {
System.out.println("enter answer");
String answer = inputReader.readString().trim().toUpperCase();
if (answer.length() == 1 && "ABCD".indexOf(answer) != -1) {
driverAnswers[index] = answer;
index++;
} else {
System.out.println("Answers can only be A,B,C or D");
}
}
}
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)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am new to java
This is my first real project (card game: Blackjack)
I made a test class and was told to use print-lines to try and pinpoint my problem, however I cannot comprehend why the null exception keeps showing up. I don't have anything set to null, and my array has been initialized using the "new". I can also post the IO class, however i'm fairly certain that the issue is not within that.
public static void main(String[] args) {
// Initializing just a single player
Player x = new Player();
// Quick test to make sure it reads the initial value of 0
System.out.println(x.getMoney());
// Testing user input using an IO class given
System.out.println("How much would you guys like to play with?(Bet money)");
double y = IO.readDouble();
x.addMoney(y);
System.out.println(x.getMoney());
// Successfully prints out the value y
Player[] total = new Player[4];
total[1].addMoney(y);
System.out.println(total[1].getMoney());
// returns the null pointer exception error
}
Here is my Player class
package Blackjack;
public class Player {
private Hand hand = new Hand();
private double currentMoney = 0;
private double bet = 0;
public void takeCard(Card h) {
hand.addCardToHand(h);
}
public double getBet() {
return bet;
}
public double getMoney() {
return currentMoney;
}
public void betMoney(double k) {
currentMoney = -k;
bet = +k;
}
public void addMoney(double k) {
currentMoney = currentMoney + k;
}
public void resetBet() {
bet = 0;
}
I can see maybe the problem being within my initialization of hand, however I the fact that I don't ask to return anything from the hand portion of the code leads me to believe that's not where the issue lies.
Player[] total = new Player[4];
total[1].addMoney(y);
when you initialize an object array, it is "filled" with null references. So in this case, total[1] will return null, unless you assign a Player instance to index 1: total[1] = new Player();
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
This is the following code. I have to make the array null for a purpose, then when I initialize the array components to 1, it shows null pointer exception. How to handle this?
public static void main(String[] args) {
double[] a;
a=null;
if(a==null)
for(int i=0;i<12;i++)
a[i]=1;
}
You need to create an array object and assign it to the array variable before trying to use the variable. Otherwise you are creating the very definition of a NullPointerException/NPE: trying to use (dereference) a reference variable that refers to null.
// constant to avoid "magic" numbers
private static final int MAX_A = 12;
// elsewhere in code
if (a == null) {
a = new double[MAX_A]; // you need this!
for (int i = 0; i < a.length; i++) {
a[i] = 1.0;
}
}
a[i]=1 // That's the problem.
You are trying to assign a value, without actually allocating memory (aka, not initializing). Indirectly you are trying to invoke a operation on NULL object which obviously results in Null Pointer Exception.
So
if(a == null){
a = new double[12];
//other for loop logic
}
will solve the problem. 12 is the size of the array (The number of double value it can hold/store).
You have to create the array before initialization -
double[] a;
a=null;
if(a==null){
a = new double[12];
for (int i = 0; i < a.length; i++) {
a[i] = 1.0;
}
}
Since double array a is null when you are trying to access the array element like this -
a[i]=0;
It produces NullPointerException.
At the first place why don't you make it NULL while declaring the variable double[] a = null;
The reason why you are getting NullPointer is because you are trying to access it when it is NULL a[i]=1;. This is as good as String name = null; name.toString(); You are doing some operation on an NULL value so getting NullPointer.
Just initialize it and then try to access it and you will not get NullPointer. This is like you should first allocate some memory and then try to access the memory location, when no memory is allocated, you will get NullPointer which tells you that there is no memory allocated yet. Hope this helps.