Exception in thread "main" java.lang.NullPointerException? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am a beginner in java programming. I am trying to recreate a simplified version of the card game war. I ran my program which is posted below and it came back with this error:
Exception in thread "main" java.lang.NullPointerException
at cardgame.BuildDeck(cardgame.java:36)
at cardgame.main(cardgame.java:60)
I have been trying to solve this issue on my own through research, but I could not solve it. I was wondering if anyone can help me. If you do need any other information about my program, please just ask. Thanks in advance!
-FGxMatta
public class cardgame
{
static class TheCard
{
// Java getter & setter
private String CardName;
private int CardRank;
private int Chosen;
public TheCard(int rank, String name)
{
this.CardName = name;
this.CardRank = rank;
this.Chosen = 0;
}
}
#SuppressWarnings("null")
private static TheCard[] BuildDeck()
{
TheCard[] TheDeck = null;
String[] Cards = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
String[] Suits = {"Spades","Hearts","Diamonds","Clubs"};
int[] Rank = {2,3,4,5,6,7,8,9,10,11,12,13,14};
int cardnumber = 0;
for (int i = 0; i < Cards.length; i++)
{
for (int j = 0; j < Suits.length; j++)
{
String deckcard = Cards[i];
String suitcard = Suits[j];
String cardname = deckcard + "-" + suitcard;
TheDeck[cardnumber] = new TheCard(Rank[i], cardname);
cardnumber++;
}
}
return TheDeck;
}
private static TheCard GetRandomCard(TheCard[] OrderedDeck)
{
TheCard thecard;
int random = (int) (51*Math.random ());
thecard = OrderedDeck[random];
if (thecard.Chosen == 0 ) // if available...
{
thecard.Chosen = 1; // mark it taken...
return thecard;
}
else
{
return GetRandomCard(OrderedDeck);
}
}
public static void main(String args[])
{
TheCard[] OrderedDeck = BuildDeck();
System.out.println ("Welcome, Prepare for War!");
int decksize = OrderedDeck.length;
int player1wincount = 0;
int player2wincount = 0;
int tiecount = 0;
for (int cardcount = 0; cardcount < decksize;)
{
TheCard Player1 = GetRandomCard(OrderedDeck);
cardcount++;
TheCard Player2 = GetRandomCard(OrderedDeck);
cardcount++;
System.out.println ("Player 1's card is: " + Player1.CardName);
System.out.println ("Player 2's card is: " + Player2.CardName);
if (Player1.CardRank > Player2.CardRank)
{
System.out.println("Player 1 wins this hand");
player1wincount++;
}
if (Player1.CardRank < Player2.CardRank)
{
System.out.println("Player 2 wins this hand");
player2wincount++;
}
if (Player1.CardRank == Player2.CardRank)
{
System.out.println("Player 1 and Player 2 played the same valued card");
tiecount++;
}
}
System.out.println ("Player 1 won " + String.valueOf(player1wincount) + " hands");
System.out.println ("Player 1 won " + String.valueOf(player2wincount) + " hands");
System.out.println ("There were " + String.valueOf(tiecount) + " ties");
}
}

Replace:
TheCard[] theDeck = null;
with:
TheCard[] theDeck = new TheCard[Cards.length * Suits.length];
and move it to below the declarations for Cards and Suits.

Null Pointer Exception is a situation in code where you try to access/ modify an object which has not been initialized yet. It essentially means that object reference variable is not pointing anywhere and refers to nothing or ‘null’. A simple example can be:
package au.com.copl;
public class Demo{
public static void main(String[] args) {
String d = null;
System.out.println(d.toString()); // d is un-initialized and is null
}
}

right here
TheDeck[cardnumber] = new TheCard(Rank[i], cardname);
you never initialized TheDeck. You probably want something like
TheDeck = new TheCard[52];
before you start putting things in the array.
as a note, java convention is that variable names be camel cased. So "CardName" should be cardName. Just a convention.

TheCard[] theDeck = null; ?
dont you need to inialize it?

You should also use new in main method:
TheCard[] OrderedDeck = BuildDeck();
should be replaced by:
TheCard[] OrderedDeck = new BuildDeck();

Related

Error in Java Method Cant get it to print to the console

I'm not sure where I went wrong but I could use some help. I'm new to JAVA and I'm not sure where I'm going wrong. Just trying to get the items in the public void method to print to my console.
public class HomersDonutShop {
public static void main (String[] args) {
//Creates flavor array
String[] donutFlavors = new String[4];
donutFlavors[0]= "Chocolate";
donutFlavors[1]= "Vanilla";
donutFlavors[2]= "Chocolate With Sprinkles";
donutFlavors[3]= "Blueberry";
//default is chocolate. prints string with array selected
System.out.println("You picked " +donutFlavors[0]+"."+" Great choice!!");
//creates donut rating
final int donutRating[] = new int[5];
donutRating[0] = 1;
donutRating[1] = 2;
donutRating[2] = 3;
donutRating[3] = 4;
donutRating[4] = 5;
//default is 5 prints string with array selected
System.out.println("You gave " +donutFlavors[0]+" donuts"+" a rating of"+ " "+donutRating[4]);
}
public void makeDonuts(){
donutCount = donuCount + 1;
System.out.println("Time to mke more donuts."+" MMMMMMMM DOOOONNNUUUUTSSS.");
}
public void buyMoreIngredients() {
int ingredients = 10;
while (ingredients >= 10)
System.out.println(ingredients);
ingredients--;
if (ingredients <=1) {
System.out.println("Time to go shopping");
}
}
}

Java array of queues printing out only last element within for loop in print method

I spent several hours working on this and even had my professor look at this and it seems to be printing out just the last element in the for loop. It seems to allows me to add the data structure information and initialize the array queue but it only print out the last element. Here is the sufficient code to assist with the question.
static int MAX;
static final int amount = 6;
static boolean [] openflag;
static queue [] Clinic;
static String [] Doctor;
final static String HEADING = "The clinic moniter of Dylan Rychlik";
public static void Listpaitents( ) {
Paitent[] array;
int queuechoice;
JOptionPane.showMessageDialog(null, "Which doctor would you like to
print?");
String InputString = JOptionPane.showInputDialog(null,Doctor, HEADING,
JOptionPane.QUESTION_MESSAGE);
queuechoice = Integer.parseInt(InputString);
if (openflag[queuechoice -1 ] == false){
JOptionPane.showMessageDialog(null, "Sorry, that doctor is not aviable");
}
else {
//Paitent[] array = null;
int limit;
limit = Clinic[queuechoice -1 ].getSize();
array = Clinic[queuechoice -1 ].toArray();
System.out.println(array[0]);
System.out.println(array[1].Print());
System.out.println(array[2].Print());
//int size = Clinic[queuechoice -1].getSize();
//System.out.println(limit);
int x; String out = " Members of the list are: \n";
// boolean exit = false;
for(x = 0; x < limit; x++) {
out += array[x].Print() + "\n";
//System.out.println(out);
// System.out.println(Clinic[queuechoice].toString() + "\n");
}
System.out.println(limit);
JOptionPane.showMessageDialog(null,out);
}
}
Here this is the array() method in the queue clas
public Paitent[] toArray() {
int x;
Paitent[] Array = new Paitent[Length];
queuenode Current = rear;
for (x = 1; ((Current != null) && (x <= Length));x++) {
Array[x-1] = new Paitent();
Array[x-1].update(Current.info);
Current = Current.next;
// System.out.println( Array[x-1].Print());
}
//System.out.println( Array[x-1].Print());
return Array;
}
Any finally here this is the print method
public String Print() {
String outputString;
outputString = "Paitent: " + "-" + name + "\n" + " Telephone number
telephone + " ID " + ID;
return outputString;
}
Any help you can give is really appreciated. I really have spent hours analyzing the code to come up a solution. Its a bulky program.

Why do object arrays in my ArrayList fail to retain their values?

I am creating a program in Java to simulate evolution. The way I have it set up, each generation is composed of an array of Organism objects. Each of these arrays is an element in the ArrayList orgGenerations. Each generation, of which there could be any amount before all animals die, can have any amount of Organism objects.
For some reason, in my main loop when the generations are going by, I can have this code without errors, where allOrgs is the Organism array of the current generation and generationNumber is the number generations since the first.
orgGenerations.add(allOrgs);
printOrgs(orgGenerations.get(generationNumber));
printOrgs is a method to display an Organism array, where speed and strength are Organism Field variables:
public void printOrgs(Organism[] list)
{
for (int x=0; x<list.length; x++)
{
System.out.println ("For organism number: " + x + ", speed is: " + list[x].speed + ", and strength is " + list[x].strength + ".");
}
}
Later on, after this loop, when I am trying to retrieve the data to display, I call this very similar code:
printOrgs(orgGenerations.get(0));
This, and every other array in orgGenerations, return a null pointer exception on the print line of the for loop. Why are the Organism objects loosing their values?
Alright, here is all of the code from my main Simulation class. I admit, it might be sort of a mess. The parts that matter are the start and simulator methods. The battle ones are not really applicable to this problem. I think.
import java.awt.FlowLayout;
import java.util.*;
import javax.swing.JFrame;
public class Simulator {
//variables for general keeping track
static Organism[] allOrgs;
static ArrayList<Organism[]> orgGenerations = new ArrayList <Organism[]>();
ArrayList<Integer> battleList = new ArrayList<Integer>();
int deathCount;
boolean done;
boolean runOnce;
//setup
Simulator()
{
done = false;
Scanner asker = new Scanner(System.in);
System.out.println("Input number of organisms for the simulation: ");
int numOfOrgs = asker.nextInt();
asker.close();
Organism[] orgArray = new Organism[numOfOrgs];
for (int i=0; i<numOfOrgs; i++)
{
orgArray[i] = new Organism();
}
allOrgs = orgArray;
}
//graphsOrgs
public void graphOrgs() throws InterruptedException
{
JFrame f = new JFrame("Evolution");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(1000,500);
f.setVisible(true);
Drawer bars = new Drawer();
//System.out.println(orgGenerations.size());
for (int iterator=0;iterator<(orgGenerations.size()-1); iterator++)
{
printOrgs(orgGenerations.get(0));
//The 0 can be any number, no matter what I do it wont work
//System.out.println("first");
f.repaint();
bars.data = orgGenerations.get(iterator);
f.add(bars);
//System.out.println("before");
Thread.sleep(1000);
//System.out.println("end");
}
}
//prints all Orgs and their statistics
public void printOrgs(Organism[] list)
{
System.out.println("Number Of Organisms: " + list.length);
for (int x=0; x<list.length; x++)
{
System.out.println ("For organism number: " + x + ", speed is: " + list[x].speed + ", and strength is " + list[x].strength + ".");
}
System.out.println();
}
//general loop for the organisms lives
public void start(int reproductionTime) throws InterruptedException
{
int generationNumber = 0;
orgGenerations.add(allOrgs);
printOrgs(orgGenerations.get(0));
generationNumber++;
while(true)
{
deathCount = 0;
for(int j=0; j<reproductionTime; j++)
{
battleList.clear();
for(int m=0; m<allOrgs.length; m++)
{
if (allOrgs[m].alive == true)
oneYearBattleCheck(m);
}
battle();
}
reproduction();
if (done == true)
break;
orgGenerations.add(allOrgs);
printOrgs(orgGenerations.get(generationNumber));
generationNumber++;
}
printOrgs(orgGenerations.get(2));
}
//Checks if they have to fight this year
private void oneYearBattleCheck(int m)
{
Random chaos = new Random();
int speedMod = chaos.nextInt(((int)Math.ceil(allOrgs[m].speed/5.0))+1);
int speedSign = chaos.nextInt(2);
if (speedSign == 0)
speedSign--;
speedMod *= speedSign;
int speed = speedMod + allOrgs[m].speed;
if (speed <= 0)
speed=1;
Random encounter = new Random();
boolean battle = false;
int try1 =(encounter.nextInt(speed));
int try2 =(encounter.nextInt(speed));
int try3 =(encounter.nextInt(speed));
int try4 =(encounter.nextInt(speed));
if (try1 == 0 || try2 == 0 || try3 == 0 || try4 == 0 )
{
battle = true;
}
if(battle == true)
{
battleList.add(m);
}
}
//Creates the matches and runs the battle
private void battle()
{
Random rand = new Random();
if (battleList.size()%2 == 1)
{
int luckyDuck = rand.nextInt(battleList.size());
battleList.remove(luckyDuck);
}
for(int k=0; k<(battleList.size()-1);)
{
int competitor1 = rand.nextInt(battleList.size());
battleList.remove(competitor1);
int competitor2 = rand.nextInt(battleList.size());
battleList.remove(competitor2);
//Competitor 1 strength
int strengthMod = rand.nextInt(((int)Math.ceil(allOrgs[competitor1].strength/5.0))+1);
int strengthSign = rand.nextInt(2);
if (strengthSign == 0)
strengthSign--;
strengthMod *= strengthSign;
int comp1Strength = strengthMod + allOrgs[competitor1].strength;
//Competitor 2 strength
strengthMod = rand.nextInt(((int)Math.ceil(allOrgs[competitor2].strength/5.0))+1);
strengthSign = rand.nextInt(2);
if (strengthSign == 0)
strengthSign--;
strengthMod *= strengthSign;
int comp2Strength = strengthMod + allOrgs[competitor2].strength;
//Fight!
if (comp1Strength>comp2Strength)
{
allOrgs[competitor1].life ++;
allOrgs[competitor2].life --;
}
else if (comp2Strength>comp1Strength)
{
allOrgs[competitor2].life ++;
allOrgs[competitor1].life --;
}
if (allOrgs[competitor1].life == 0)
{
allOrgs[competitor1].alive = false;
deathCount++;
}
if (allOrgs[competitor2].life == 0)
{
allOrgs[competitor2].alive = false;
deathCount ++ ;
}
}
}
//New organisms
private void reproduction()
{
//System.out.println("Number of deaths: " + deathCount + "\n");
if (deathCount>=(allOrgs.length-2))
{
done = true;
return;
}
ArrayList<Organism> tempOrgs = new ArrayList<Organism>();
Random chooser = new Random();
int count = 0;
while(true)
{
int partner1 = 0;
int partner2 = 0;
boolean partnerIsAlive = false;
boolean unluckyDuck = false;
//choose partner1
while (partnerIsAlive == false)
{
partner1 = chooser.nextInt(allOrgs.length);
if (allOrgs[partner1] != null)
{
if (allOrgs[partner1].alive == true)
{
partnerIsAlive = true;
}
}
}
count++;
//System.out.println("Count 2: " + count);
partnerIsAlive = false;
//choose partner2
while (partnerIsAlive == false)
{
if (count+deathCount == (allOrgs.length))
{
unluckyDuck=true;
break;
}
partner2 = chooser.nextInt(allOrgs.length);
if (allOrgs[partner2] != null)
{
if (allOrgs[partner2].alive == true)
{
partnerIsAlive = true;
}
}
}
if (unluckyDuck == false)
count++;
//System.out.println("count 2: " + count);
if (unluckyDuck == false)
{
int numOfChildren = (chooser.nextInt(4)+1);
for (int d=0; d<numOfChildren; d++)
{
tempOrgs.add(new Organism(allOrgs[partner1].speed, allOrgs[partner2].speed, allOrgs[partner1].strength, allOrgs[partner2].strength ));
}
allOrgs[partner1] = null;
allOrgs[partner2] = null;
}
if (count+deathCount == (allOrgs.length))
{
Arrays.fill(allOrgs, null);
allOrgs = tempOrgs.toArray(new Organism[tempOrgs.size()-1]);
break;
}
//System.out.println(count);
}
}
}
Main method:
public class Runner {
public static void main(String[] args) throws InterruptedException {
Simulator sim = new Simulator();
int lifeSpan = 20;
sim.start(lifeSpan);
sim.graphOrgs();
}
}
Organism class:
import java.util.Random;
public class Organism {
static Random traitGenerator = new Random();
int life;
int speed;
int strength;
boolean alive;
Organism()
{
speed = (traitGenerator.nextInt(49)+1);
strength = (50-speed);
life = 5;
alive = true;
}
Organism(int strength1, int strength2, int speed1, int speed2)
{
Random gen = new Random();
int speedMod = gen.nextInt(((int)Math.ceil((speed1+speed2)/10.0))+1);
int speedSign = gen.nextInt(2);
if (speedSign == 0)
speedSign--;
speedMod *= speedSign;
//System.out.println(speedMod);
int strengthMod = gen.nextInt(((int)Math.ceil((strength1+strength2)/10.0))+1);
int strengthSign = gen.nextInt(2);
if (strengthSign == 0)
strengthSign--;
strengthMod *= strengthSign;
//System.out.println(strengthMod);
strength = (((int)((strength1+strength2)/2.0))+ strengthMod);
speed = (((int)((speed1+speed2)/2.0))+ speedMod);
alive = true;
life = 5;
}
}
The problem lies in the graphOrgs class when I try to print to check if it is working in preparation for graphing the results. This is when it returns the error. When I try placing the print code in other places in the Simulator class the same thing occurs, a null pointer error. This happens even if it is just after the for loop where the element has been established.
You have code that sets to null elements in your allOrgs array.
allOrgs[partner1] = null;
allOrgs[partner2] = null;
Your orgGenerations list contains the same allOrgs instance multiple times.
Therefore, when you write allOrgs[partner1] = null, the partner1'th element becomes null in all the list elements of orgGenerations, which is why the print method fails.
You should create a copy of the array (you can use Arrays.copy) each time you add a new generation to the list (and consider also creating copies of the Organism instances, if you want each generation to record the past state of the Organisms and not their final state).

Why is this getting NullPointerException & ArrayIndexOutOfBoundsException errors [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
Getting a NullPointerError on line 24 (second for loop) and an arrayoutofindexexception on the main method. I have no idea how to solve this and an explanation would be much appreciated. Please help!
Edit: 'NullPointerError' solved, just needed to initialize the ArrayList for it, but still can't work out the 'ArrayOutOfIndexException' error.
import java.util.*;
public class SnackBar
{
private Random randomizer;
private String[] flavours;
private SnackMachine barMachine;
ArrayList<Student> students;
public SnackBar(int numStudents, int packetsBarMachine, int costPacket)
{
randomizer = new Random();
flavours = new String[] {"prawn cocktail", "tango cheese", "natural", "paprika", "salt and vinegar"};
barMachine = new SnackMachine(packetsBarMachine, costPacket);
students = new ArrayList<Student>();
for(int i = 0; i < packetsBarMachine; i++)
{
barMachine.addPack(new PackOfCrisps(randomFlavour()));
i++;
}
for(int j = 0; j < numStudents; j++)
{
students.add(new Student(randomFlavour(), barMachine));
j++;
}
}
public String randomFlavour()
{
int random = randomizer.nextInt(flavours.length);
return flavours[random];
}
public void describe()
{
System.out.println("The SnackBar has " + students.size() + " hungry students.");
System.out.println("The Snackmachine has:");
System.out.println(barMachine.countPacks("prawn cocktail") + " packets of prawn cocktail crisps,");
System.out.println(barMachine.countPacks("tango cheese") + " packets of tango cheese crisps,");
System.out.println(barMachine.countPacks("natural") + " packets of natural crisps,");
System.out.println(barMachine.countPacks("paprika") + " packets of paprika crisps,");
System.out.println(barMachine.countPacks("salt and vinegar") + " packets of salt and vinegar crisps.");
}
public void runSnackBar(int nSteps)
{
int step = 1;
while(step <= nSteps)
{
System.out.println("Time Step " + step);
describe();
int atRandom = randomizer.nextInt(students.size());
students.get(atRandom).snackTime();
step++;
}
}
public static void main(String[] args)
{
SnackBar bar = new SnackBar (Integer.parseInt(args[4]), Integer.parseInt(args[20]), Integer.parseInt(args[5]));
bar.runSnackBar(Integer.parseInt(args[30]));
}
}
First thing, you should initialize the ArrayList<Student> students list.
Integer.parseInt(args[30]) is also suspicious, since for that not to throw an exception, you have to supply 31 command line arguments. Same goes for all your other attempts to access elements of args array without checking its length first.

Stuck with Pascal's Triangle in Java

Ok, I need to have a class that re-creates the Pascal Triangle. We are using BlueJ and I can't get my arrays to access each other.
Here's the code:
public class PascalTriangle {
private int currentLineNumber;
private int[] previousLineArray;
private int[] nextLineArray;
public void firstLine()
{
currentLineNumber = 1;
System.out.println("1");
}
public void nextLine()
{
if (currentLineNumber == 1) {
int [] previousLineArray = new int [(currentLineNumber+1)];
previousLineArray[0] = 1;
previousLineArray[1] = 1;
System.out.println("1 1");
currentLineNumber = 2;
}
else if(currentLineNumber >= 2) {
for (int lineCount = currentLineNumber; lineCount <= currentLineNumber; lineCount++) {
int [] nextLineArray = new int [(lineCount+1)];
nextLineArray[0] = 1;
System.out.print(nextLineArray[0] + " ");
for (int nextLineCount = 1; nextLineCount < lineCount; nextLineCount++) {
// The next line is the line with the NullPointerException
nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1)
+ previousLineArray[(nextLineCount)]]);
System.out.print(nextLineArray[(nextLineCount)] + " ");
}
nextLineArray[(lineCount)] = 1;
System.out.print(nextLineArray[(lineCount)] + "\n");
previousLineArray = nextLineArray;
}
currentLineNumber = currentLineNumber+1;
}
}
}
The class will compile but as I get to the third line, which should read 1 2 1, I get a java.lang.NullPointerException at PascalTriangle.nextLine(PascalTriangle.java:29) it highlists the nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) line. Why will the nextLineArray take the information from previousLineArray which is set when the nextLine() method is called for the first time?
Any help would be appreciated :) Thanks.
the problem is the following:
in the line where int [] previousLineArray = new int [(currentLineNumber+1)]; - you create a local array that shadows your member and only visible inside of if statement. Then when you come to this line: nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) it uses your member array that was not init.

Categories