java.lang.NullPointerException when passing a boolean through an array - java

I'm trying to make a game for my Java class, but I keep getting a NPE. I know that it means one of the variables being passed is a null, but I have no idea where. I have checked all variables involved. I believe it may be an issue with initializing the arrays, but I'm still not seeing what I've done wrong. I've checked around stack overflow and I have seen NPEs due to various reasons, but I can't find a solution that works on mine.
public class Inventory{
public int gold = 0;
private Item[] itemListArray = new Item[30];
private JButton[] itemButtonArray = new JButton[30];
private JButton buttonBack = new JButton("Back");
private static final String HOME = "Home";
public Inventory() {
for(int i = 1;i < 31; i++)
{
itemListArray[i].emptySlot = true; //Here is where the NPE hits
}
}}
That is where the NPE calls for the error
public class Item {
protected String name = "";
protected int def = 0;
protected int stack = 100;
protected boolean stackable = false;
protected boolean consume = false;
boolean emptySlot = true;
protected ImageIcon icon;
public Item(){
}
public boolean isArmor()
{
if(def >= 1)
{
return true;
} else {
return false;
}
}
public boolean isConsumable()
{
if(consume = true)
{
return true;
} else {
return false;
}
}
public boolean isEmpty()
{
if(emptySlot = true)
{
return true;
} else {
return false;
}
}
Here is the declaration of Item.
Please Answer soon to my issue, I can't seem to figure it out.

Item[] itemListArray = new Item[30];
This code just creates an array that contains null values, you need to initializes each individual value in the array.
for(int i = 1;i < 31; i++)
{
itemListArray[i].emptySlot = true; //Here is where the NPE hits
}
And this cycle will cause ArrayIndexOutOfBoundsException later because in Java valid array indexes start from 0 and go to array.length-1 (0 to 29 in your case), while this code will try to access itemListArray[ 30 ].

It isn't sufficient for you to instantiate your array, you must also populate it with objects. Otherwise each index contains null by default.
private Item[] itemListArray = new Item[30];
for (int i = 0; i < itemListArray.length; i++) {
itemListArray[i] = new Item();
}

You instantiate your array with private Item[] itemListArray = new Item[30]; which creates an array of type Item with 30 null entries.
When you call itemListArray[i].emptySlot in your loop in the constructor you are accessing a variable from a null object.
You will have to instantiate any Item objects in your array in the loop in your constructor (or elsewhere) before you can access any variables or invoke any methods from them.
Also your for loop is skipping the first element. The first element in Java has an index of 0.

I guess you may haven't understand initialization in java.you just initialize a array ,but it haven't refer to the real object.
code like this will help:
for(int i = 1;i < 31; i++){
Item item = new Item();
item.emptySlot = true;
itemListArray[i] = item; //Here is where the NPE hits
}
try to use a constructor in Item class is much better,hope it work.

Creating an array of objects defaults all of them to null. You need to put an object into each element of the array to get rid of this problem.
for (int i = 0; i < itemListArray.length; i++) {
itemListArray[i] = new Item();
}
for (int j = 0; j < itemButtonArray.length; j++) {
itemButtonArray[j] = new JButton();
}

Related

Declaring a new Array with a larger size within a method that does not return

I am currently filling in a section of code and in it one of the methods I have to make a new array double the size and fill it in with the old values, which I did, but how do I make it so that the new array is the one that is used from now on if the method doesn't return anything?
private void upSize()
{
String[] biggerArr = new String[theArray.length*2];
for( int i = 0; i < theArray.length; i++)
biggerArr[i] = theArray[i];
}
So obviously this code is built to not return anything, but when it gets called somewhere like here, how do I actually increase the size of that array so that it can fit the new "Added" element.
public boolean add( T element ){
if (size() == theArray.length) upSize();
theArray[count++] = element;
return true;
}
I'm sorry if this was something that already has an answered thread, I did a lot of searching through and couldn't find anything that touched on this specifically.
You have to return new array and assign it to the existing reference, like this:
private String[] upSize()
{
String[] biggerArr = new String[theArray.length*2];
for( int i = 0; i < theArray.length; i++)
biggerArr[i] = theArray[i];
return biggerArr;
}
public boolean add( T element ){
if (size() == theArray.length) theArray = upSize();
theArray[count++] = element;
return true;
}
But look at java.util.ArrayList, you won't have to reinvent the wheel :)

Why does these constructors have an error?

public class CharacterList {
private char [] charArray;
private int count;
public CharacterList(int arraySize){
charArray = new char[arraySize];
count = 0;
}
private int indexOf(char searchingChar) {
int a = 0;
for (int i = 0; i < charArray.length; i++) {
if(charArray[i] == searchingChar)
a = i;
else
a = -1;
}
return a;
}
public boolean addCharacter(char characterToAdd){
if(indexOf(characterToAdd) == -1){
doubleArrayCapacity();
count ++;
return true;
} else if(indexOf(characterToAdd) == 0){
charArray[0] = characterToAdd;
count++;
return true;
} else
return false;
}
}
I need to construct all the methods given in the attached list. I have done these many so far and the remaining are hard to get. Could someone:
1.) Check if the code I written till now is correct?
2.) Help me with the other constructors
Thank you in advance
Use an IDE, it will tell you that line 31 and 32 are the errors:
c cannot be resolved to a variable
Fix:
Rename c to characterToAdd
The method doubleArrayCapacity() is undefined for the type CharacterList
Fix:
Create method doubleArrayCapacity()
private void doubleArrayCapacity() {
// TODO Auto-generated method stub
}
And your code will compile (doesn't mean that it's working!).
Contructor is ok. Only one think I've found incorrect it your code is lack of method public void doubleArrayCapacity(). Probably you have forgoted implement or you avoid when copy source code here.
Another cause, where could be error is call of this contractor. How you call it? With argument or without? How that looks like?
public void doubleArrayCapacity() {
//create new array of char, which is double length
char [] newCharArray = new char[this.charArray.length*2];
//prescribe values from old array to new one
for(int i=0; i<this.charArray.length-1; i++) {
newCharArray[i] = this.charArray[i];
}
//set newCharArray set new value of your field charArray
this.charArray = newCharArray;
}

Initialize array of objects(which has an array) in Java

I am relatively new to java, and this is only the second time I have ever tried to design a program that has an array of class objects. I am having trouble because when I go into debug mode, it is showing me that the arrays are being built correctly. However, when I try to build a string or even print to the console, I am getting a null pointer exception.
I am trying to make an array of Slot class objects.
public class C {
int slotNum;
Slot[] s;
public C(int byteSize, int slotNum){
this.slotNum = slotNum;
Slot[] s = new Slot[slotNum]; //create an array of slots
for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
s[i] = new Slot(byteSize);
}
display();
}
And the Slot class has its own array, block[], constructed by a value passed in through its constructor.
public class Slot {
boolean v;
short block[];
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
short block[] = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
Later in the program I then try to print to the console or build a string and it always breaks when I try to use any element in the slot[] in the C class.
Have I instantiated and initialized my 2 different arrays correctly?
public class C {
int slotNum;
Slot[] s;
public C(int byteSize, int slotNum){
this.slotNum = slotNum;
s = new Slot[slotNum]; //create an array of slots
for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
s[i] = new Slot(byteSize);
}
display();
}
Try something like these instead
public class Slot {
boolean v;
short block[];
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
block = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
Replace
short block[] = new short[byteSize];
with
block = new short[byteSize];
Always use a this operator to initialize in a constructor so that you may differentiate clearly between local variables and instance variables
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
this.block = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}

Calling a Method With Parameters In Another Class

I'm having trouble passing a method with a parameter to another class.
In my main class I declare:
searchMap search = new searchMap();
search.search(null, 0);
In my other class, I have that as:
public boolean search(int[][] map, int fuel)
{
int totalSum = 0;
int row[] = new int[map.length];
boolean valid = true;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (i == j)
continue;
valid = valid && possiblePath(map, fuel, 0, i, j);
}
}
if(totalSum <= fuel)
{
System.out.println("This map is solvable :)");
return true;
}
else
{
System.out.println("This map is NOT solvable :(");
return false;
}
}
And I keep getting:
Exception in thread "main" java.lang.NullPointerException
at searchMap.search(searchMap.java:33)
at loadMap.load(loadMap.java:117)
at loadMap.main(loadMap.java:23)
I've tried everything and can't break from the NullPointerException. I've tried calling other ints, I've tried calling map[][], and I've had no success. Help would be greatly appreciated!!
EDIT:
public static void main(String[] args)
{
loadMap load = new loadMap();
load.load();
}
public void load()
{
JFileChooser chooser = new JFileChooser();
Scanner readLine = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
try {
readLine = new Scanner(selectedFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int setMapSize = 0;
int i;
int j;
int toNode;
int edge;
setMapSize = readLine.nextInt();
readLine.nextLine();
int rowCounter = 0;
int[][] map = new int[setMapSize][setMapSize];
int[] row = new int[setMapSize];
int sum = 0;
int totalSum = 0;
System.out.println("MAP: " + map.length);
do
{
String line = readLine.nextLine();
Scanner newLine = new Scanner(line);
do
{
toNode = newLine.nextInt();
edge = newLine.nextInt();
map[rowCounter][toNode] = edge;
} while(newLine.hasNextInt());
rowCounter++;
newLine.close();
} while (rowCounter < setMapSize);
int fuel = readLine.nextInt();
System.out.println("Fuel: " + fuel);
readLine.close();
}
searchMap search = new searchMap();
search.search(null, 0);
}
You are passing in a null map, then turning around and calling this line.. map will be null and you are unable to call .length on a null.
int row[] = new int[map.length];
You could fix this by adding a check to make sure the parameter map is not null
public boolean search(int[][] map, int fuel) {
boolean valid = false;
if (map != null) {
int totalSum = 0;
int row[] = new int[map.length];
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map.length; j++) {
if (i == j) continue;
valid = valid && possiblePath(map, fuel, 0, i, j);
}
}
if (totalSum <= fuel) {
System.out.println("This map is solvable :)");
return true;
} else {
System.out.println("This map is NOT solvable :(");
return false;
}
}
return valid;
}
it is because you put null in for the map.
null is normally fine as a placeholder but when you do things like:
map.length
you are asking for a property of a null value.
null values have no properties.
try putting a test map in instead.
A null pointer exception occurs probably means that you are trying to access something which doesn't exist.
In this case, your int[][] map is null and in the 2nd line of you search method, you are trying to get the map.length. Make any sense to you? Java is unable to get the length of an array which does not exist, thus giving your the nullPointerException.
You can solve your problem by either:
Pass in an array reference instead of null when calling your method.
Do this in your main:
searchMap search = new searchMap();
int[][] map = new int [5][5]; //Just an example
search.search(map, 0); //Pass in an existing 2D array instead of null
OR
Add a check to see whether array is null
You can do it as below:
if (map== null)
length = 0;
else
length = map.length;
int row[] = new int[length];
Personally, as a habit, I will also suggest your refrain from using similar names for methods and objects.
You're calling:
search.search(null, 0);
so you pass null as the map parameter..
Which will cause NullPointerException starting here since a null does not have a length property:
int row[] = new int[map.length];
You need to pass in your map instead of passing a null value. Providing your SearchMap class would probably help.
Now that I see you're declaring map:
int[][] map = new int[setMapSize][setMapSize];
Then when you want to pass in the map to the search function, you should call
search.search(map, 0);
int[][] is the type of the variable map, so there is no need to use [][] when using the variable.
You also declared map inside the if so it's out of scope by the time you call it for search.
I think you want to move it inside that if statement since you don't want to search when there's no file.
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
// ...
int[][] map = new int[setMapSize][setMapSize];
// ...
searchMap search = new searchMap();
search.search(map, 0);
}

Java array NullPointerException

The code block is listed below:
public static Vertex[] computeSubGraph(Vertex[] AdjList, int[] retiming)
{
Vertex[] subGraph = new Vertex[AdjList.length];
for (int i = 0; i < AdjList.length; i++) {
System.out.println(i);
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
subGraph[i].predecessor = AdjList[i].predecessor;
subGraph[i].mark = AdjList[i].mark;
subGraph[i].starTime = AdjList[i].starTime;
subGraph[i].finishTime = AdjList[i].finishTime;
for (int j = 0; j < AdjList[i].inArcList.size(); j++) {
ArcNode old = AdjList[i].inArcList.get(j);
ArcNode newNode = new ArcNode(old.adjVex, old.arcWeight);
subGraph[i].outArcList.add(newNode);
subGraph[old.adjVex].inArcList.add(newNode);
}
}
return subGraph;
}
This is the Vertex class:
public class Vertex implements Comparable<Vertex> {
public int arcWeight;
public int preDelay;
public boolean infinite = true;
public int nodeDelay = 0;
public Vertex predecessor = null;
public ArcNode firstArc = null;
public int mark = 0;
public int starTime;
public int finishTime;
public ArrayList<ArcNode> inArcList = new ArrayList<ArcNode>();
public ArrayList<ArcNode> outArcList = new ArrayList<ArcNode>();
}
Actually, I just want to copy the element in AdjList to a new array subgraph. But the error message shows that "java.lang.NullPointerException" and shows the problem lies in "subGraph[i].nodeDelay = AdjList[i].nodeDelay;" line.
I tested by printing to the console. And found the AdjList.length is 8 and the problem occurs in the very first round; And even when I only write "subGraph[i].nodeDelay;" without assigning any value to it, it also shows the wrong message.
Any idea on this? Thanks in advance.
Add it inside the loop:
subGraph[i] = new Vertex();
You first need to instantiate an object (subGraph[i] in your case) before accessing it.
The answer is: uninitialized variable. You did initialize subGraph to be an array, but you did not initialize subGraph[i].
When you create an object array in java, it's automatically initialized with null values. It's your responsibility to loop on the array an populate it with references to new objects.
In your case, you should assign Vertex objects to all array positions.
You need to create a Vertex instance and place it in the array prior to setting any fields.
Something like:
public static Vertex[] computeSubGraph(Vertex[] AdjList, int[] retiming)
{
Vertex[] subGraph = new Vertex[AdjList.length];
for (int i = 0; i < AdjList.length; i++) {
subGraph[i] = new Vertex(); // adding instance prior to setting fields.
System.out.println(i);
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
subGraph[i].predecessor = AdjList[i].predecessor;
subGraph[i].mark = AdjList[i].mark;
subGraph[i].starTime = AdjList[i].starTime;
subGraph[i].finishTime = AdjList[i].finishTime;
for (int j = 0; j < AdjList[i].inArcList.size(); j++) {
ArcNode old = AdjList[i].inArcList.get(j);
ArcNode newNode = new ArcNode(old.adjVex, old.arcWeight);
subGraph[i].outArcList.add(newNode);
subGraph[old.adjVex].inArcList.add(newNode);
}
}
return subGraph;
}
On add
subGraph[i] = new Vertex();
before this line
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
Because subGraph[i] is initially null . So subGraph[i].nodeDelay will obviously throw a NullPointerException, because you are trying to access or modify the field of a null object. Array of references will always be initialized with elements of null references by default.

Categories

Resources