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];
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);
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.
I am having some trouble looping through an array with objects, inside the class. I wrote a little demo here so you can follow:
Tank tanks[] = new Tank[2];
tanks[0] = new Tank();
tanks[1] = new Tank();
tanks[0].doStuff(tanks);
doStuff(Tank[] tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i].equals(this)) continue;
// Do stuff
}
}
So, I have an array with the type Tank. Then I call the method doStuff inside the Tank class. The method takes the array and loops through it. And then I want to do stuff to every tank that is not the current instance of the class. I hope you can make sense out of my code and this description.
The problem is that I get nullPointerException for if (tanks[i].equals(this))
What am I doing wrong here?
That means that tanks[i] is null. (or that your overridden equals() method has a bug)
You need to check for that.
if you want to compare the IDs of your object you can use == instead of .equals()
doStuff(Tank tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i] == this) {
continue;
}
// Do stuff
}
}
When I run this code:
public class Tank {
public static void main(String[] args) {
Tank tanks[] = new Tank[2];
tanks[0] = new Tank();
tanks[1] = new Tank();
tanks[0].doStuff(tanks);
}
public void doStuff(Tank[] tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i].equals(this)) continue;
// Do stuff
}
}
}
No error happens. Therefore, you've probably overridden .equals, and that is where the NullPointerException is occurring. The other possibility is that your simple example doesn't accurately reflect where your bug is occurring.
I hope someone could help me please, I need to pass a String from the method below to the method below that. I have looked on the interent and got it working on test programs but can't seem to get it working on mine, it's been 3 hours, 3 pages of google and a book lol. Sorry if this is easy but I really have no idea.
What I need to do... I need to pass the variable "Hex" from the method "WMDBAudio" to the method "hexConverter". I hope this makes sense, thanks for your help in advance it's is apperciated!
public class WMDBAudio{
public String WMDBAudio1(String fileInfo) throws IOException{
//code removed as there is quite a lot
int m = 0;
while (m != 1){
for (int count = 0; count < 3; count++){
hexIn = in.read();
s = Integer.toHexString(hexIn);
if(s.length() < 2){
s = "0" + Integer.toHexString(hexIn);
}
temp = temp + s;
}
if ("000000".equalsIgnoreCase(temp)){
m = 1;
hex = entry;
}
entry = entry + temp;
temp = "";
}
}
}
//Hex Converter method
public class hexConverter{
public static void hexConverter(String t){
WMDBAudio w = new WMDBAudio();
String hex = "";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2){
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);
}
}
By convention you name Java classes starting with upper cases. So hexConverter should be renamed to HexConverter.
You generally invoke another class from a class in this format:
MyClass myClass = new MyClass();
after that you can use myClass object to access methods (not private) of MyClass.
Make the following 2 lines change as I have commented.
public class WMDBAudio{
public String WMDBAudio1(String fileInfo) throws IOException{
//code removed as there is quite a lot
int m = 0;
while (m != 1){
for (int count = 0; count < 3; count++){
hexIn = in.read();
s = Integer.toHexString(hexIn);
if(s.length() < 2){
s = "0" + Integer.toHexString(hexIn);
}
temp = temp + s;
}
if ("000000".equalsIgnoreCase(temp)){
m = 1;
hex = entry;
}
entry = entry + temp;
temp = "";
}
//add these 2 lines
hexConverter hexConv = new hexConverter();
hexconv.hexConverter(hex);
}
}
You could set hex as a private attribute of the class, thus being acessible to both methods (and all others of the same class).
This assuming that calling the first one doesn't necessarily require calling the second one. If that's the case then you could just call hexConverter from WMDBAudio with an extra parameter for the hex String.
EDIT: Nvm that just saw they are two different classes. Well, you could save the hex as a private variable on both classes and have a GetHex() method on the WMDBAudio class. You then use the value returned by that method to create a hexConverter class that takes Hex as a parameter to its constructor thus allowing something of the sort:
WMDBAudio audio = new WMDBAudio()
...
hexConverter hexconv = new hexConverter(audio.GetHex())
Or just supply an additional parameter to the hexConverter function allowing you to write something like this:
WMDBAudio audio = new WMDBAudio()
...
hexConverter hexconv = new hexConverter()
hexconv.hexConverter(audio.GetHex())
Since hexConverter is a static method in hexConverter class,
you can access the method as
hexConverter.hexConverter(hex);
You need not create a new object to access the method. The method performs a common operation and does not change the state of the object. Hence, you can use it as above, pass the String and get the result.
You might also need to import hexConverter class if it is in a different package.
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 :)