Java NullPointerException - Short Program - java

I'm new in programming in Java and I do not understand what's going on in my code.
It tells me:
Exception in thread "main" java.lang.NullPointerException
at Main.Country.addMine(Country.java:37)
at Main.Main.main(Main.java:21)
Java Result: 1
My main.java is simple:
Continent Europe = new Continent("Europe");
Country asd = new Country("asd", Europe);
Mine mine = new Mine(100,100,100,100);
System.out.println(mine == null);
asd.addMine(mine); //dies here
this is addMine method:
public void addMine(Mine mine) {
System.out.println(mine == null);
this.mines.add(mine); //dies here
this.iron += mine.iron;
this.gold += mine.gold;
this.stone += mine.stone;
this.wood += mine.wood;
System.out.println("Mine has been successfully added to the country with the given values."
);
and Mine.java is:
public class Mine implements Building { //Building is an empty interface :)
protected int iron;
protected int gold;
protected int stone;
protected int wood;
public Mine(int iron, int gold, int stone, int wood) {
this.iron += iron;
this.gold += gold;
this.stone += stone;
this.wood += wood;
}
}
As You can see I wrote 2 println-s and both of them were false, so the object exists! I don't understand why it shows NullPointerException :(

If this is failing:
this.mines.add(mine); //dies here
... then I suspect mines is a null reference. You haven't shown any declaration for it or initialization - but that should be your first port of call. Chances are it's just a case of changing:
private List<Mine> mines;
to
private List<Mine> mines = new ArrayList<Mine>();
or something similar.

Yes, mine could be not null but what about mines? Which I guess it's a ArrayList<Mine> or something like that, did you inizialize it as mines = new ArrayList<Mine>()? (or whichever collection it is)

Null pointer exception is thrown when you invoke method on reference that is null.
this.mines.add(mine); //dies here
this.mines reference is obviously equal to null.
Also try to make your reference variables names start with lowercase letters.
Continent Europe = new Continent("Europe");
->
Continent europe = new Continent("Europe");
Names with starting uppercase letters are 'reserved' for classes.
It's considered a good style in Java.

You code fails in the
this.mines.add(mine);
at County class.
In order to bypass the error you should create a local variable inside the County class(in case you dont have it) which will be
private List<Mine> mines;
and you will initialise it by adding the following
mines=new LinkedList<Mine>();
The above thing can be written in one line of code but that is up to you.
private List<Mine> mines=new LinkedList<Mine>();
You can use any other implementation of List.

Related

java.util.LinkedList<ClassName> cannot be converted to ClassName

I am on my way to learning java, so please bear with me on this one, even if its very simple to you.
I'm working with two LinkedLists:
private LinkedList<BloodDonor> x;
private LinkedList<BloodDonor> y;
public List()
{
x = new LinkedList<>();
y = new LinkedList<>();
}
I have a method called heroDonors that searches the LinkedList x to see if there are any people who donated blood more than 50 times. If so, that donor gets added to LinkedList y and removed from LinkList x. If no donors who donated more than 50 times are present, an empty LinkedList of y is returned.
I need the LinkedList y to be returned by the method, but I get the error java.util.LinkedList<BloodDonor> cannot be converted to BloodDonor.
public BloodDonor heroDonors()
{
int donations = 50;
for (BloodDonor donor : x) {
int number = donor.getNumberOfDonations();
if (donations < number) {
y.add(donor);
x.remove(donor);
}
if (donations > number) {
}
}
return y;
}
Could anyone explain why I am getting this error?
If you want to return a List of BloodDonors you have to actually make your method of that type:
public LinkedList<BloodDonor> heroDonors() {
LinkedList<BloodDonor> result = new LinkedList<>();
...
return result;
}
BTW: I think in this case you should not use a field y but declare a local variable on order to avoid side effects. You might also consider returning the base type List<BloodDonor> instead, this will better allow to use another collection if needed (and I would never call a application class List).
Change
public BloodDonor heroDonors()
to
public List<BloodDonor> heroDonors()

Java: I keep getting an error when trying to call the shooterExperiments method. I'm not sure what I'm doing wrong or exactly how to call a method

The problem I'm having is with the last line. I get an error at this section that says "cannot find symbol". This is not my entire program, only the first section.
public class Chap6Project
{
public double shooterExperiment(int dualsPerExperiment, String[] shooters, double[] accuracies, ProbabilitySupplier p)
{
shooters[0] = "aaron";
shooters[1] = "bob";
shooters[2] = "charlie";
String aaron = shooters[0];
String bob = shooters[1];
String charlie = shooters[2];
accuracies[0] = 0.33;
accuracies[1] = 0.5;
accuracies[2] = 1.0;
int duelCount = 0;
boolean aaronAlive = true;
boolean bobAlive = true;
boolean charlieAlive = true;
Chap6Project project = new Chap6Project();
ProbabilitySupplier random = new ProbabilitySupplier();
double rateOfSuccess = project.shooterExperiment(1000, shooters, accuracies, random);
while (duelCount < 1000)
{
int aaronKills = 0;
int aaronWin = 0;
double aaronAccuracy = random.getAsDouble();
if (aaronAccuracy == 0.33)
{
if (charlieAlive != true)
{
aaron.shooterExperiment(1000, bob, accuracies[1], random);
You declare the aaron variable like so:
String aaron = shooters[0];
and then try to use it like so:
aaron.shooterExperiment(1000, bob, accuracies[1], random);
and do this all within this method:
public double shooterExperiment(int dualsPerExperiment, String[] shooters,
double[] accuracies, ProbabilitySupplier p)
The aaron variable is a String and Strings have no shooterExperiment(...) method. Perhaps you meant to call this method on a different variable? Given what you've posted it's very hard to say. It looks like you're trying to call the shooterExperiment method from within itself, meaning making a recursive call, and doing so with incorrect method parameters and on the wrong object, a String object, none of which makes sense.
You'll want to clarify your problem and what your code is supposed to be doing greatly.
Other issues:
Your code suffers from the parallel array anti-pattern, a program structure that makes it very easy to create bugs. Instead create a class to encapsulate your shooter, including its name, health, accuracy, etc. and use a single collection of Shooter objects.

Why another branch is unreachable in my code?

Why the output of the following code is always suck. How to get happy as the output? Why the happy branch is unreachable?
public class HowToMakeStackoverflowBetter {
private static final int HUMAN_PATIENCE = 10;
private List<Member> members = new ArrayList<>();
private int atmosphere = -10;
private Random r = new Random();
public HowToMakeStackoverflowBetter(int size) {
for (int i = 0; i < size; i++) { members.add(new Member()); }
}
public Member pick() { return members.get(r.nextInt(members.size())); }
public class Member {
private int patience = HUMAN_PATIENCE;
private Question question = null;
public Member() { patience = r.nextInt(patience+1) + atmosphere; }
public void vote(Question q) {
if (patience >= 0) {
voteUp(q);
} else {
voteDown(q);
}
}
public void ask() {
question = new Question();
for (Member member : members) {
member.vote(question);
}
}
private void voteUp(Question q) { ++q.vote; }
private void voteDown(Question q) { --q.vote; }
public String toString() {
return (question.vote >= 0)? "Happy!" : "Suck!";
}
}
public class Question { private int vote; }
public static void main(String[] args) {
HowToMakeStackoverflowBetter stackoverflow = new HowToMakeStackoverflowBetter(100);
Member me = stackoverflow.pick();
me.ask();
System.out.println(me);
}
}
After a 1000 times loop, it gives us 1000 sucks. I remember 2 or 3 years ago, this was not the case. Something changed.
Two problems. First:
linkedList::linkedList(){
*sentinel.last=sentinel;
*sentinel.next=sentinel;
sentinel.str="I am sentinel!!";
};
sentinel is your member variable, and .last is its pointer to another node. This hasn't been initialised, so trying to use it is undefined behaviour. In practice, it's effectively pointing at a random address in (or out of) memory, and you attempt to dereference the pointer then copy the entire sentinel object over the node at the imagined pointed-to address: i.e. you try to copy the 3 pointers in the sentinel node member variable to a random address in memory.
You probably want to do this:
linkedList::linkedList()
{
sentinel.last = &sentinel;
sentinel.next = &sentinel;
sentinel.str = "I am sentinel!!";
}
Secondly, you explicitly call the destructor for linkedList, which results in undefined behaviour when the compiler-arranged destruction is performed as the object leaves the stack scope it's created in - i.e. at the end of main().
I suggest you change node.str to be a std::string, as in any realistic program you'll want to be able to handle variable text, and not just point to (constant) string literals. As is, if you mix string literals and free-store allocated character arrays, you'll have trouble knowing when to call delete[] to release the memory. You could resolve this by always making a new copy of the string data to be stored with new[], but it's safer and easier to use std::string.
Since you allocated it as a local variable, your mylist will be destroyed automatically upon exiting main. Since you've already explicitly invoked its destructor, that leads to undefined behavior (attempting to destroy the same object twice).
As a quick guideline, essentially the only time you explicitly invoke a destructor is in conjunction with placement new. If you don't know what that is (yet), that's fine; just take it as a sign that you shouldn't be invoking destructors.
You forgot to initialize sentinel
In code below you are trying to initialize sentinel (which is not yet constructed) with sentinel(same thing). So you have to pass something to constructor which can be used to initialize your member variable sentinel
*sentinel.last=sentinel;
Also no need to call destructor like this. Destructor will be called once your myList goes out of scope.
myList.~linkedList();
the program may crash, with this:
*sentinel.last=sentinel;
*sentinel.next=sentinel;
sentinel is not initialized sot i has random value on stack.
You're trying to de-reference the pointers last and next of member variable sentinel when they are not yet initialized.
And these de-references *sentinel.last=sentinel *sentinel.next=sentinel are causing the crash because without assigning the values to pointers you're changing the value pointed by the pointers.
You can do like this
sentinel.last=&sentinel;
sentinel.next=&sentinel;
And as pointed out by other explicit destructor calls aren't need here.

my compiler is saying that I have an incompatible type. Java

It says that the numbers 125,100 are incompatible types in the line: _die1 = newDie(125,100);
i dont understand it because in the NewDie method it takes int 2 ints, so it should work fine...?! Basically this program creates dice rolls and I am trying to get it to display the roll #2
import java.awt.*;
// The panel which holds the two dice
import javax.swing.*;
public class DicePanel extends JPanel
{
// instance variables
private Die _die1, _die2;
private int _roll;
/**
* Constructor for objects of class DicePanel
*/
public DicePanel()
{
// initialise instance variables
super();
setBackground(Color.GRAY);
_die1 = new Die(125,100);
_die2 = new Die(250,100);
roll();
}
// display the dice in the panel
public void paintComponent(Graphics pen)
{
super.paintComponent(pen);
Graphics2D aBetterPen = (Graphics2D)pen;
_die1.paint(aBetterPen);
_die2.paint(aBetterPen);
}
// roll both dice and display them
public void roll()
{
// _die1 = new Two(125,100);
// _die2 = new Three(250,100);
_die1 = newDie(125,100);
// _die2 = DicePanel.newDie(250,100);
//repaint();
}
// retrieve the value of each die
public int getDie1()
{
return _die1.getValue();
}
public int getDie2()
{
return _die2.getValue();
}
// factory method for a die
public void newDie(int x, int y){
//_roll = randomNumber(1,6);
_die1 = new Two(x,y);
// _die2 = new Three(x,y);
}
// random number generator to return and integer between two integers, inclusive.
public static int randomNumber(int low, int high){
return low + (int)(Math.random()*(high-low+1));
}
}
newDie returns void which is obviously incompatible with _die's type of Die.
There is no line that says newDie(125,100). There is, however, a line that says new Die(125,100) ... and that means something very different. It is a constructor invocation not a method call.
So either:
you are calling the newDie method, and it is complaining because newDie returns void, or
you are invoking the Die constructor as new Die(125, 100) and the formal and actual parameter types don't match.
Given the error message is complaining about 125 and 100, I think the 2nd explanation is the more likely one. But you didn't include the Die constructor declaration in your Question, so I can't be sure.
I should also add that _die1, _die2 and _roll are coding style violations according to most Java coding styles ... and in particular by the coding style that is recommended by Oracle. You have a good reason for being different (and personal preference is NOT a good reason) then you should write your Java code to conform to a mainstream style.
Your code's indentation is also inconsistent with any coding style I've ever seen ... and should also be fixed.
If you are writing code purely for your own benefit, and nobody else is ever going to have to read it, then your code style is your own business. But if you ever want anyone (e.g. your lecturer, your co-workers, StackExchange readers) to read it, then style is important.

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