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;
}
}
Related
I am trying to assign value of FileData's instance variable in File class
At first FileData's nextIndex should all be -1, and then it should be assigned the value of counter
I've tried get,set and FileData array to assign value but its not working and
gives NULL POINTER EXCEPTION
I've tried:
class FileData
{
int nextIndex = 0;
public void setIndex()
{
for(int i=0; i<10;i++)
{
nextIndex = -1;
}
}
}
class File
{
public static void main(String args[])
{
FileData[] FD = new FileData[10];
for(int i=0; i<5;i++)
{
FD[i].nextIndex = i;
}
}
}
When working with objects, you first have to create an instance. All I've done is add a declarator in the loop and formatted the code:
class FileData {
int nextIndex = 0;
public void setIndex() {
for (int i = 0; i < 10; i++) {
nextIndex = -1;
}
}
}
class File {
public static void main(String args[]) {
FileData[] FD = new FileData[10];
for (int i = 0; i < 5; i++) {
FD[i] = new FileData();
FD[i].nextIndex = i;
}
}
}
Note that the FileData[] FD = new FileData[10]; bit just declares an array of the type FileData, and does not yet give each object its needed storage space.
The array elements here are null:
FileData[] FD = new FileData[10];
First you need to create the objects:
for(int i=0; i < FD.length ;i++)
{
FD[i] = new FileData();
FD[i].nextIndex = i;
}
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);
}
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();
}
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.
So im working on some homework and I can't figure out how to make an String array[a] pass into a method in another class and be recorded as a String array there. This is kinda hard to explain since its new to me, but here is what I'm trying to do.
Tester Program:
Purse c = new Purse();
c.addCoin("Quarter");
c.addCoin("Penny");
c.addCoin("Nickel");
c.addCoin("Dime");
Purse d = new Purse();
d.addCoin("Nickel");
d.addCoin("Dime");
d.addCoin("Dime");
d.addCoin("Quarter");
System.out.println(c.sameCoins(d));
System.out.println("Expected: false");
Purse class:
public boolean sameCoins(Purse other)
{
if (array1.length != array2.length)
{
return false;
}
int same = 0;
for (int i = 0; i < array1.length; i++)
{
for (int x = 0; x < array2.length; x++)
{
if (array2[x].equals(array1[i]))
{
same++;
break;
}
}
}
return same==array1.length;
}
I know array1 and array2 aren't proper variable/names for the arrays but that just to substitute the idea I'm trying to get at.
If array is field in Purse class than other purse array can be accessed in function sameCoins with other.array
you are returning same==array1.length and you initially set same = 0 and never incremented it.