Null Pointer Exception [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am working on some project in java.
Here I'm stuck at this problem and not able to figure out where I am going wrong.
I have made two classes: Test and Child.
When I run the code I am get a NullPointerException.
package com.test;
public class Test {
child newchild = new child();
public static void main(String[] args) {
new Test().method();
}
void method() {
String[] b;
b = newchild.main();
int i = 0;
while (i < b.length) {
System.out.println(b[i]);
}
}
}
package com.test;
public class child {
public String[] main() {
String[] a = null;
a[0] = "This";
a[1] = "is";
a[2] = "not";
a[3] = "working";
return a;
}
}

Here's the problem:
String[] a = null;
a[0]="This";
You're immediately trying to dereference a, which is null, in order to set an element in it. You need to initialize the array:
String[] a = new String[4];
a[0]="This";
If you don't know how many elements your collection should have before you start populating it (and often even if you do) I would suggest using a List of some sort. For example:
List<String> a = new ArrayList<String>();
a.add("This");
a.add("is");
a.add("not");
a.add("working");
return a;
Note that you have another problem here:
int i=0;
while(i<b.length)
System.out.println(b[i]);
You're never changing i, so it will always be 0 - if you get into the while loop at all, you will never get out of it. You want something like this:
for (int i = 0; i < b.length; i++)
{
System.out.println(b[i]);
}
Or better:
for (String value : b)
{
System.out.println(value);
}

This is the problem:
String[] a = null;
a[0]="This";

They highlighted the problem of your probably the definition of null pointer exception would give you an idea what and where to find the problem in future. From java api doc, it defined what is npe and under what situation it will be thrown. Hope it help you.
Thrown when an application attempts to use null in a case where an object is required. These include:
* Calling the instance method of a null object.
* Accessing or modifying the field of a null object.
* Taking the length of null as if it were an array.
* Accessing or modifying the slots of null as if it were an array.
* Throwing null as if it were a Throwable value.

package test;
public class Test {
child newchild = new child();
public static void main(String[] args) {
new Test().method();
}
void method()
{
String[] b;
b = newchild.main();
int i=0;
while(i<b.length){
System.out.println(b[i]);
i++;
}
}
}
package test;
public class child {
public String[] main() {
String[] a = {"This","is","not","Working"};
return a;
}

Related

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..
}
}
}

NullPointerException with an ArrayList inside of a HashMap [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am attempting to use an arraylist inside of a hashmap to create and iterate counters for different characters fed to the processLine method. I think I have declared all of the variables and the catch statements should handle the cases in which there isn't an entry in the hashmap, but I am still getting a NullPointerException on the curCounts.set(i, 1); line in the second catch statement. I've probably made some dumb mistake, but I can't figure out what it is.
HashMap<Character, ArrayList<Integer>> charCounts;
public DigitCount() { charCounts = new HashMap<>(); }
public void processLine (String curLine) {
int length = curLine.length();
char curChar;
ArrayList<Integer> curCounts;
Integer curCount;
for(int i = 0; i < length; i++){
curChar = curLine.charAt(i);
try {
curCounts = charCounts.get(i);
} catch (NullPointerException ex) {
curCounts = new ArrayList<>();
}
try {
curCount = curCounts.get(i);
curCount++;
curCounts.set(i, curCount);
} catch (NullPointerException ex) {
curCounts.set(i, 1);
}
charCounts.put(curChar, curCounts);
}
linesProcessed++;
System.out.println("---------------------------" + linesProcessed);
}
Edit: Yes, I did call DigitCount.
public static void main(String args[]) throws Exception
{
//creates an instance of the digitCount object and starts the run method
DigitCount counter = new DigitCount();
counter.run(args[0]);
}
if charConts doesn't contain i (as in charCounts.get(i)), then it won't throw a NullPointerException, it will return null. Therefore you should be using an if and not a trycatch as in:
curCounts = charCounts.get(i);
if(curCounts==null)
curCounts = new ArrayList<>();
Edit: Alternatively if you are using java 8 you can do
curCounts = charCounts.getOrDefault(i,new ArrayList<Integer>());
and it will automatically default to creating a new ArrayList if it doesn't contain one

Why doesnt string.equals("astring") work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
Why don't I get 20 after delivering e.g. "Obsidian" to Test(String pStr) if I call getMatInt() ?
Also tried .toString() after all String-declariations, also declarated e.g. "Obsidian" as new String a. Nothing works.
getBonus is aways returning a 0 instead of a 20/30/... .
I already tried "Obsidian" and "obsidian", both doesnt work for me ...
public class test
{
private String str;
private int matInt;
private int bonus;
private int magic;
public test(int pMagic, String pStr)
{
int magic = pMagic;
str = pStr;
}
private void materialEquals()
{
if(str.equals("Obsidian"))
{
matInt = 20;
}
.....
}
private void calcBonus()
{
materialEquals();
bonus = magic * matInt;
}
public int getBonus()
{
calcBonus();
return bonus;
}
}
try:
public int getMatInt()
{
materialEquals();
return matInt;
}
There is no reason for this in your constructor: str = new String(pStr);, just use str = pStr.
In fact, you might be better off setting matInt in your constructor:
public test(String pStr)
{
str = pStr;
materialEquals();
}
And depending on how many materials you have, you might want to look into using enumeration.
Ok after your edits:
public int getBonus()
{
calcBonus(); //bonus won't be calculated otherwise
return bonus;
}
After further edits:
Your constructor is wrong, you're not initializing int magic. Try this constructor instead.
public test(int pMagic, String pStr)
{
this.magic = pMagic; //int magic = pMagic was a new variable only in the constructor scope
this.str = pStr;
calcBonus();
}
Also you might as well calculate the bonus on construction.
You will need to call materialEquals() so that 20 can be assigned to matInt upon equals comparison, as integers are always initialized to default value 0 upon declaration.

Return the stack element at a given index without modifying the original Stack in Java

Ok I was recently asked this in an interview, and I am intrigued. Basically I have a stack with a certain set of values, I want to pass the stack object in a function and return the value at certain index. The catch here is that after the function is complete, I need the stack unmodified; which is tricky because Java passes reference by value for objects. I am curious if there is purely a java way to do using push(), pop(), peek(), isempty() and primitive data type. I am against copying the elements into an array or string. Currently the cleanest I have got is using clone, find the code below:
import java.util.Stack;
public class helloWorld {
public int getStackElement( Stack<Integer> stack, int index ){
int foundValue=null;//save the value that needs to be returned
int position=0; //counter to match the index
Stack<Integer> altStack = (Stack<Integer>) stack.clone();//the clone of the original stack
while(position<index)
{
System.out.println(altStack.pop());
position++;
}
foundValue=altStack.peek();
return foundValue;
}
public static void main(String args[]){
Stack<Integer> stack = new Stack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
helloWorld obj= new helloWorld();
System.out.println("value is-"+obj.getStackElement(stack,4));
System.out.println("stack is "+stack);
}
}
I understand that cloning is also copying, but that's the basic flaw I am aiming to remove. Stripped down I am asking if I would be actually be able to pass the stack's value instead of passing the value of its reference.
Thanks in advance.
int position =5;
Integer result = stack.get(position);
Java Doc here
If you cannot use another stack, you can cheat and abuse a local variable on the call stack for the same purpose by making a recursive method:
public static <T> T getStackElement(Stack<T> stack, int index) {
if (index == 0) {
return stack.peek();
}
T x = stack.pop();
try {
return getStackElement(stack, index - 1);
} finally {
stack.push(x);
}
}

stackoverflowerror null

The error i am having here is a infinite or near infinite loop in my method calls and class's creating other class's constructors. What my program is trying to do is semi-randomly generate survey results based off actual statistics. I would highly appreciate not only some insight in whats going wrong here. But some advice and pointers on how to prevent this from happening and ways to analyze the error messages by myself. I get how some of the work but like i stated below i am new to programming im a freshman in college so programming is new to me. Thanks in advance and sorry for my previous post, thought i would take the time to give you guys an appropriate one.
Im new to programming this is my 2nd project ive done on my own so im sorry if its not the best.
This is my Test class:
public Tester()
{
randomGenerator = new Random();
probability = new Probability();
stats = new Statistics();
double chance = randomGenerator.nextDouble();
double gender = probability.getProbabilityOfMale();
if(chance > gender)
{
male = false;
stats.incrementFemale();
}else{
male = true;
stats.incrementMale();
}
age = randomGenerator.nextInt(49)+16;
int range = stats.getNumberOfQuestion();
for(int i=0;i<range;i++)
{
probabilities = probability.probOfAnswer(i);
answers = probability.getAnswers(i);
chance = randomGenerator.nextDouble();
int size = probabilities.size();
for(int j=0;j<size;j++)
{
double qTemp = chance - probabilities.get(j);
if(qTemp <= 0.0)
{
Answer aTemp = answers.get(j);
aTemp.incrementCounter();
answers.set(j,aTemp);
}
}
}
}
Statistics class:
public ArrayList<Answer> getAnswers(int index)
{
temp = survey.getAnswers(index);
return temp;
}
public int getMale()
{
return male;
}
public int getFemale()
{
return female;
}
public int getNumberOfQuestion()
{
return numberOfQuestion;
}
public void incrementNumberOfQuestion()
{
numberOfQuestion++;
}
public void incrementMale()
{
male++;
}
public void incrementFemale()
{
female++;
}
and probability class:
public Probability()
{
stats = new Statistics();
probOfAnswer = new ArrayList<Double>(0);
}
public ArrayList<Double> probOfAnswer(int index)
{
temp = stats.getAnswers(index);
int size = temp.size();
for(int i=0;i<size;i++)
{
aTemp = temp.get(i);
for(int j=0;j<size;j++)
{
Answer aTemp = temp.get(j);
sum += (double)aTemp.getCounter();
}
double number = (double)aTemp.getCounter();
probOfAnswer.add(number/sum);
sum = 0;
}
return probOfAnswer;
}
public ArrayList<Answer> getAnswers(int index)
{
temp = stats.getAnswers(index);
return temp;
}
public ArrayList<Double> getProbofAnswer()
{
return probOfAnswer;
}
public void probabilityOfMale()
{
double male = (double)stats.getMale();
double female = (double)stats.getFemale();
probabilityOfMale = male / (male + female);
}
public double getProbabilityOfMale()
{
return probabilityOfMale;
}
These are the only real important parts where the loop exsists the rest of the code is not needed to be uploaded.
Im having difficulty uploading my error message on this site its not accepting it as code in the code insert, then it wont let me submit the message afterwards so im going to upload the code elseware and link it.
http://forum.overdosed.net/index.php/topic/56608-this-is-unimportant/
But i dont know how long that forum will let me keep that post there ><
at Question.<init>(Question.java:17)
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Question.<init>(Question.java:17)
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Probability.<init>(Probability.java:19)
You need to check why Question is creating Statistics object and again Statistics is trying to create Question object leading to infinite recursion. As the line numbers are given you can take a look at corresponding lines.
Judging by the stack trace, the problem lies in three parts which you haven't shown us - the Question and Statistics constructors and the Survey.addQuestion method:
From the stack trace:
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Question.<init>(Question.java:17)
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Question.<init>(Question.java:17)
So your Question constructor is calling the Statistics constructor. But the Statistics constructor is then calling Survey.addQuestion, which is in turn calling the Question constructor.
It feels to me like there's much more construction going on than is really useful. Why would a Statistics constructor need to add anything to a survey? I wouldn't expect a Statistics class to even know about surveys and questions.
It's entirely possible that a lot of this can be fixed by passing a reference to an existing object to the constructors - so the Probability constructor may be better taking a Statistics reference in its constructor and using that for its stats field than creating a new Statistics object itself. It's hard to say without knowing what these classes are really meant to represent though... which may be part of the problem. Do you have a firm grasp of what the responsibility of each class is? Think about that carefully before making any code changes.
We don't have the relevant source code, but the error message says what's wrong:
Tester creates a Probability
Probability constructor creates a Statistics
Statistics constructor calls Survey.addQuestion()
addQuestion() creates a Question
Question creates a Statistics (goto 3 and loop infinitely)
I think you should probably pass objects around rather than creating them each time.

Categories

Resources