I'm new to Java and I'm implementing a class (CenterTable) that contains a nested class (CenterData). Inside the enclosing class, I want to create an array of type CenterData. The code can be seen below:
public class CenterTable {
public class CenterData {
public int userId;
public double distance;
public double elevation;
public int point_00;
public int point_01;
public int point_10;
public int point_11;
public CenterData() {
userId = 0;
distance = 0;
elevation = 0;
point_00 = 0;
point_01 = 0;
point_10 = 0;
point_11 = 0;
}
} // end of CenterData class
public static CenterData[] centers = new CenterData[7064];
public static double centerMaxDistance = 0;
}
Whenever I try to access or set an element of the array centers:
CenterTable.centers[1].beam_user = 1;
System.out.println(CenterTable.centers[1].beam_user);
I get an error: Exception in thread "main" java.lang.NullPointerException
If I move the class CenterData out of CenterTable and into it's own java class, I don't get an issue like that.
I'm kind of stuck at this point, if any one has any tips/hints that would be great.
Thanks in advanced!
You are getting NullPointerException because you are trying to access beam_user on center[1] but it refers to null as of now.
When an array is created, all the values are default values.
The default value for a reference type is null
you need to create object first
CentreTable.centers[1] = new CentreData();
For creating all objects,
for(int i = 0; i<= centers.length ; i++){
centers[i] = new CenterData();
}
After your array elements are referring to actual objects, you can do as follows
centers[1].beam_user = 1;
You've created an array of CenterData objects, but that's just a bunch of slots that you can then fill CenterDatas into. You have to actually create them, either all at once (using a for loop) or as needed (by checking whether centers[i] == null and creating a new one if necessary).
public static CenterData[] centers = new CenterData[7064];
All the elements are null. You must put CenterData instances in the array.
Related
The class is called Exposicion and has a String and an INT value, so I used it as an array to grab some input from the user.
class Exposicion {
public String nombreExpo;
public int duracionExpo;
Exposicion(String nombreExpo, int duracionExpo) {
this.nombreExpo = nombreExpo;
this.duracionExpo = duracionExpo;
}
}
With the Function SortExpo I plan to copy only the values of the array as long as the INT values don't add up to 180, but java flags an error when doing:
arrExpoT[posHor].nombreExpo = arrExpoS[k].nombreExpo;
This is the whole function
void SortExpo(Exposicion[] arrExpoS,int posicion,Exposicion[] arrExpoT){
int poshor=0;
int total=0;
for (int k = 0; k < posicion; k++) {
if ( total < 180 || arrExpoS[poshor].nombreExpo != "TOMADO123") {
arrExpoT[poshor].nombreExpo = arrExpoS[k].nombreExpo;
arrExpoT[poshor].duracionExpo = arrExpoS[k].duracionExpo;
arrExpoS[poshor].nombreExpo = "TOMADO123";
total = total + arrExpoS[k].duracionExpo;
poshor++;
} else {
k = posicion;
}
}
}
Error
I've added the .java file in this link
Also Main.java if this helps
You are getting a NullPointerException because "expo1" and "sala1" variables are both null. You have to pass a reference to an object on both variables. Something like this:
class SalaExpo(){
Exposicion[] expo1=new Exposicion[100];
}
public class ConsoleMenu {
private SalaExpo sala1;
void execute(){
sala1 = new SalaExpo();
}
}
Also you should poblate the sala1.expo1 array, like this (don't know if this is what you are intending but you should do this in order not to get a NullPointerException) :
void GuardarExpo(Exposicion[] arrExpoG,int posicion,Exposicion[] arrSala) {
/*
Bunch
of
code
*/
arrExpoG[posicion] = new Exposicion(inputNombre,inputDuracion);
arrSala[posicion]=arrExpoG[posicion];
}
Finally, you should use the variable "posicion" instead of "sala1.expo1.length" to pass as argument to the "imprimirExpo" method, since the array "sala1.expo1" has a length of 100, that means a lot of null elements since you are not poblating it all:
ImprimirExpo(sala1.expo1,posicion);
instead of:
ImprimirExpo(sala1.expo1,sala1.expo1.length);
Why does this code not work? It seems I cannot set the variable to '10' with the Array, but with a normal object it works.
What am I doing wrong?
Class- 1
public class apples {
public static void main(String[] args) {
carrots carrotObj = new carrots();
carrotObj.setVar(5);
System.out.println(carrotObj.getVar());
carrots carrotArray[] = new carrots[3];
carrotArray[1].setVar(10);
System.out.println(carrotArray[1].getVar());
}
}
Class- 2
public class carrots {
private int var = 0;
public int getVar() {
return var;
}
public void setVar(int var) {
this.var = var;
}
}
Console Output:
5
Exception in thread "main"
java.lang.NullPointerException
at apples.main(apples.java:17)
You created an array, but when an array of objects is created, they are all initialized to null -- the default value for object reference variables. You need to create some objects and assign them to slots in the array.
carrots carrotArray[] = new carrots[3];
// Place this code
carrotArray[1] = new carrots();
carrotArray[1].setVar(10);
You could do something similar for position 0 and 2.
Additionally, the Java convention is to capitalize class names, e.g. Carrots.
You need to initialize all the elements of the array; since they are not primitive data types their default value is null.
carrots carrotArray[] = new carrots[3];
for(int i=0; i < carrotArray.length; i++){
carrotArray[i] = new carrots();
}
carrotArray[1].setVar(10);
System.out.println(carrotArray[1].getVar());
So I'm creating a class called dicegame. Here's the constructor.
public class dicegame {
private static int a, b, winner;
public dicegame()
{
a = 0;
b = 0;
winner = 2;
}
And now in the main, I'm creating an array of this object (I called it spaghetti for fun).
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[10];
spaghetti[1].roll();
}
But when I try to do anything to an element in the array, I'm getting the NullPointerException. When I tried to print one of the elements, I got a null.
You created an array, but you have to assign something (e.g. new dicegame()) to each element of the array.
My Java is slightly rusty, but this should be close:
for (int i=0; i<10; i++)
{
spaghetti[i] = new dicegame();
}
new dicegame[10]
just creates an array with 10 empty elements. You still have to put a dicegame in each element:
spaghetti[0] = new dicegame();
spaghetti[1] = new dicegame();
spaghetti[2] = new dicegame();
...
You need spaghetti[1]=new dicegame() before you call roll() on it.
Right now you are allocating an array,but don't. Place any objects in this array, so by default java makes them null.
1.you have just declared the array variable but not created the object yet. try this
2.you should start index with zero not with one.
dicegame[] spaghetti = new dicegame[10]; // created array variable of dicegame
for (int i = 0; i < spaghetti.length; i++) {
spaghetti[i] = new dicegame(); // creating object an assgning to element of spaghetti
spaghetti[i].roll(); // calling roll method.
}
Firstly,you should create object for every spaghetti input of yours.
You can start with whatever value you want. Just be sure that the size of array is matched accordingly so that you won't get ArrayIndexOutOfBounds Exception.
So,if you wanted to start with 1 and have 10 objects of the class dicegame,you will have to assign the size of the array as 11(since it starts from zero).
your main function should be like :
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[11];
//the below two lines create object for every spaghetti item
for(int i=1;i<=11;i++)
spaghetti[i]=new dicegame();
//and now if you want to call the function roll for the first element,just call it
spaghetti[1].roll;
}
Here is a method called placeShips() that I am calling via another method (which is called by a ButtonListener). But when all are called, I get a NullPointerException on the deepest nested line - System.out.println(ships[i]);. The array has been declared and initialized above this code in the constructor. It is set to be equal to a constant integer which equals 3. I've put a simple string in that printout and it works. But whenever the array gets involved, it becomes messy. What is going wrong?
NUM_SHIPS, NC_EMPTY, NC_SHIP, and all the labels/buttons have been made as well.
private Ships ships[];
*-----Constructor begins here-----*
Ships[] ships = new Ships[NUM_SHIPS];
*-----Constructor ends here-----*
ships[0] = new Ships("Aircraft Carrier", 5, false);
ships[1] = new Ships("Battleship", 4, false);
ships[2] = new Ships("Cruiser", 3, false);
public void placeShips()
{
statusLabel.setText("Press [Play]");
int shipsPlaced = 0;
do
{
int randomRow = (int)(Math.random()*ROWS);
int randomCol = (int)(Math.random()*COLS);
if (gameBoard[randomRow][randomCol] == NC_EMPTY)
{
gameBoard[randomRow][randomCol] = NC_SHIP;
shipsPlaced = shipsPlaced + 1;
for (int i = 0; i < NUM_SHIPS; i++)
{
System.out.println(ships[i]);
}
}
}while (shipsPlaced < NUM_SHIPS);
}
You have a class level array variable : private Ships ships[];, yet you define in your constructor Ships[] ships = new Ships[NUM_SHIPS];. Are you ever assigning to the class level variable? you could try
/* Class Level */
private Ships _ships[];
/* In constructor */
_ships = new Ships[NUM_SHIPS];
/* In PlaceShips() */
for (int i = 0; i < _ships.Length; i++)
{
if(_ships[i] != null)
{
System.out.println(_ships[i].toString());
}
}
If that doesn't work then debug the code to find which object is actually throwing the exception
It looks like your constructor is only initializing a local variable named ships. You say you have:
-----Constructor begins here-----*
Ships[] ships = new Ships[NUM_SHIPS];
*-----Constructor ends here-----*`
But it seems like you really want
ships = new Ships[NUM_SHIPS];
Ok, here is the code and then the discussion follows:
public class FlatArrayList {
private static ArrayList<TestWrapperObject> probModel = new ArrayList<TestWrapperObject>();
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] currentRow = new int[10];
int counter = 0;
while (true) {
for (int i = 0; i < 10; i++) {
currentRow[i] = probModel.size();
}
TestWrapperObject currentWO = new TestWrapperObject(currentRow);
probModel.add(counter, currentWO);
TestWrapperObject testWO = probModel.get(counter);
// System.out.println(testWO);
counter++;
if (probModel.size() == 10) break;
}
// Output the whole ArrayList
for (TestWrapperObject wo:probModel) {
int [] currentTestRow = wo.getCurrentRow();
}
}
}
public class TestWrapperObject {
private int [] currentRow;
public void setCurrentRow(int [] currentRow) {
this.currentRow = currentRow;
}
public int [] getCurrentRow() {
return this.currentRow;
}
public TestWrapperObject(int [] currentRow) {
this.currentRow = currentRow;
}
}
What is the above code supposed to do? What I am trying to do is load an array as a member of some wrapper object (TestWrapperObject in our case). When I get out of the loop,
the probModel ArrayList has the number of elements it is supposed to have but all have the same value of the last element (an array of size 10 with each item equal to 9). This is not the case inside the loop. If you perform the same "experiment" with a primitive int value everything works fine. Am I missing something myself regarding arrays as object members? Or did I just encounter a Java bug? I am using Java 6.
You are only creating one instance of the currentRow array. Move that inside the row loop and it should behave more like you expect.
Specifically, the assignment in setCurrentRow does not create a copy of the object, but only assigns the reference. So each copy of your wrapper object will hold a reference to the same int[] array. Changing the values in that array will make the values appear to change for all other wrapper objects that hold a reference to the same instance of the array.
i don' t want to sound condescending, but always try to remember tip #26 from the excellent pragmatic programmer book
select isn't broken
it is very rare to find a java bug. keeping this in mind often helps me to look over my code again, turn it around, and shake out the loose bits until i finally discover where i was wrong. of course asking for help early enough is very encouraged, too :)