java.lang.nullpointerexception [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have this problem with my code. Its called java.lang.nullpointerexception. and I cant seem to fix it. please help me take a look at it. Thank you. I didnt include the class name and import. class name is called CHORD. I didnt make public static since my assginemnt say dont use global variable.
private ArrayList<Integer> nodeList;
public static void main(String[] args){
CHORD obj = new CHORD();
obj.nodeList = new ArrayList<Integer>();
String filename ="";
if(args.length ==1){
filename = args[0];
obj.read(filename);
}
}
public void read(String file){
CHORD obj = new CHORD();
obj = null;
Scanner loadFile = null;
try{
loadFile = new Scanner(new File(file));
String inputLine;
while(loadFile.hasNextLine()){
inputLine = loadFile.nextLine();
String[] inputArray = inputLine.split(" ",3);
if(inputArray[0].equalsIgnoreCase("init")){
int size = Integer.parseInt(inputArray[1]);
setSizeFT(init(size));
}
else if(inputArray[0].equalsIgnoreCase("addpeer")){
System.out.println("adding");
nodeList.add(Integer.parseInt(inputArray[1]));
}
}
}
catch(FileNotFoundException x){
}
finally{
System.out.println(getFT());
loadFile.close();
}
System.out.println(getFT());
}
public void print(){
CHORD obj = new CHORD();
for(int x =0; x< obj.nodeList.size(); x++){
System.out.println(obj.nodeList.get(x));
}
}
public int init(int num){
int n = 23;
double k = Math.ceil(Math.log(n)/Math.log(2));
int size = (int)k;
return size;
}
public void setSizeFT(int size){
sizeFT = size;
}
public int getFT(){
return sizeFT;
}
}

Here's an explanation of what NullPointerException's are: http://antwerkz.com/dealing-with-nullpointerexceptions/ From the article:
The most common (and obvious to the seasoned developer) is that you didn't initialize a variable.
Looking at that line, it looks like obj.nodeList may be null. Here's how I deduced that:
I can see that obj is not null, because the first line is CHORD obj = new CHORD();. That means you didn't set obj to null.
I can tell that Integer is not null. That's a class and you're calling a static method. That can't be null because there's nothing to be assigned there.
inputArray[1] may return null, but if that were happening, your stack trace would not end on this line, it would probably end on some line inside Integer.parseInt. I'd need to see a full stack trace to be sure though. But looking at the javadoc of Integer.parseInt, it doesn't say it'll throw a NPE so that's even more evidence to rule it out.
If inputArray was null, you'd probably get the error on the first if statement so I can rule that out.
Somewhere your code needs to do a obj.nodeList = new NodeList() or something like that. I can't say for sure without seeing what the CHORD class looks like.

Related

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

String cause NullPointerException [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
This is my code. I just read file that have lines first is number then lines as string their number equal the number in first line.
import java.io.*;
import java.util.*;
class groupmember
{
int recieving;
int giving;
String name;
groupmember()
{
recieving=0;
giving=0;
//name=null;
}
public void setname (String Title)
{
this.name = new String(Title);
}
public void setrecieving(int val)
{
recieving=val;
}
public void setgiving(int val)
{
giving=val;
}
public String getname()
{
return name;
}
public int getrecieving()
{
return recieving;
}
public int getgiving()
{
return giving;
}
}
class gift1 {
/**
* #param args
*/
public static void main(String[] args) throws IOException{
BufferedReader f=new BufferedReader(new FileReader("gift1.in"));
PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter("gift1.out")));
StringTokenizer st=new StringTokenizer(f.readLine());
int NP=Integer.parseInt(st.nextToken());
int excpectedgived=0,div=0;
groupmember []groupmember=new groupmember[NP];
for(int i=0;i<NP;i++)
{
st=new StringTokenizer(f.readLine());
String name=st.nextToken();
groupmember[i].setname(name);
System.out.println(name);
}
out.close();
}
}
The problem arises on this line:
groupmember[i].setname(name);
It causes NullPointerException. I want to know why this happens.
An array of reference type variables is filled with null entries after initialization. You need
groupmember[i] = new groupmember();
before you can do:
groupmember[i].setname(name);
In future, please follow the Java Naming Conventions and have your classes start with an uppercase letter, like GroupMember (even CamelCase).
groupmember[i] is never defined, you need to add
groupmember[i] = new groupmember();
or something like that at the start of your cycle.
You have just initialised the array of type groupmember, now all the values in the array are null, in order to start using the array, you need to do .
groupmember[i] = new groupmember();
Do this: String name = ""; String have default value null if they are not initialized.

Simple OOP/private variable query- Java

Not quite sure why this won't work, when i try to compile and run it gives me a null pointer exception. I know it's super simple and probably a stupid question but I can't seem to figure it out!
import javax.swing.JOptionPane;
public class Whatever
{
private int age;
private String name;
private float salary;
public Whatever ()
{
String userName = JOptionPane.showInputDialog ("What is your name?");
Whatever listData[] = new Whatever [10];
listData[6].name = userName;
}
public static void main (String [] args)
{
Whatever testWhatever = new Whatever ();
}
}
Array of Whatever instances - all are null.
I would guess you'd have another problem with OutOfMemoryError as soon as you fix it, because when you call new to initialize the Whatever array elements they'll construct their own arrays and call new, and so on until you get OOM error.
I'll spell it out for you so you can get to the next error:
import javax.swing.JOptionPane;
public class Whatever
{
private int age;
private String name;
private float salary;
public Whatever () {
String userName = JOptionPane.showInputDialog ("What is your name?");
Whatever listData[] = new Whatever[10];
for (int i = 0; i < listData.length; ++i) {
listData[i] = new Whatever(); // This is where you'll get the OOM error. See why?
}
// You'll never get here.
listData[6].name = userName;
}
public static void main (String [] args)
{
Whatever testWhatever = new Whatever();
}
}
And you're putting Swing code in a constructor? Did you intend this as an example of how to write bad code?
Just for future reference, you should run your code in a good IDE - like IntelliJ, the best on the market - with debugging turned on and step through the code. You'll figure it out pretty quickly where the problem lies, faster than asking at SO will tell you.
So yes, it's a pretty stupid example. Hopefully you aren't writing anything like this for real.
With this
Whatever listData[] = new Whatever [10];
you initialized a new Array, but the elements in the Array are not initialized.
So you get a NullPointerException when you access listData[6].name.
You could try this:
for(int i = 0; i < listData.length; i++) {
listData[i] = new Whatever();
}
, but please do this not in the constructor itself.
Because then you would get OutOfMemoryException like duffymo said.
Try to do this directly in main for example.

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.

How to copy array from File1.java to File two.java [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
In File1.java I have-
public static int[] dataArray = new int[100];
in File2.java I am accessing it as -
private static int[] data = new int[File1.dataArray.length];
for(int i=0; i<File1.dataArray.length; i++) {
if(File1.array1[i] == 0)
continue;
data[i] = File1.array1[i];}
Is this the right way or can I do like this-
private static int[] data = File1.dataArray;
to copy it? Any help appreciated. Thanks!
Yes, you can do
private static int[] data = File1.dataArray;
But there is a HUGE DANGER doing it that way and therefore I wouldn't call it the right way to COPY arrays, because you are not REALLY copying.
See this code. It demonstrates what happens.
public class File1
{
public static int[] dataArray = new int[100];
static
{
for (int i=0; i<100; i++)
{
dataArray[i] = i;
}
}
}
public class File2
{
private static int[] data = File1.dataArray; // makes "data" refer to the SAME array as File1.dataArray
public static void main(String[] args)
{
File2 file2 = new File2();
file2.data[20] = -567; // this changes File1.dataArray also!
System.out.println(File1.dataArray[20]); // prints -567
}
}
Therefore, use System.arrayCopy() to copy arrays, as Jarrod suggested. Of course, you can also copy by writing your own code like this -
private static int[] data = new int[File1.dataArray.length];
static
{
for(int i = 0; i < File1.dataArray.length; i++)
{
data[i] = File1.dataArray[i];
}
}
Look up System.arraycopy() to copy arrays.
It isn't clear what the presented code has to do with Files as referenced in your title?
Also your presented code is incomplete, won't compile and isn't clear or idiomatic Java.
This will most likely get closed if you don't make it clearer what you want to do.

Categories

Resources