I am writing a program to mimic the "Deal or No Deal" game.
Background on Deal or No Deal: http://en.wikipedia.org/wiki/Deal_or_No_Deal
In working up to the final product, I have written various classes. However, I am trying to test one of my classes, and continue to get the NullPointerException.
I wrote a class called Box, that creates "box" objects. The box object is the actual box that a player picks. It consists of a true/false value and a double boxValue. The boolean variable denotes whether it's open/closed (true for open, false for closed). The double boxValue is the actual value assigned to the box.
public class Box {
//instance fields
private double boxValue; // the amount of $ in each box
private boolean openClose; // whether or not the box is closed
//Constructor
public Box(double boxValue) {
this.openClose = false;
this.boxValue = boxValue;
if (boxValue < 0) {
throw new IllegalArgumentException("Box value must be greater than 0");
}
}
}
I have written another class called BoxList as well. This creates a Box object array that will serve as the playing board, when combined with further classes that I am planning to write. The main idea is that the constructor in BoxList creates the array by using a passed in double array as a paramater, and then creates a Box Object array of the same length of the passed in double array, and assigns the double value of each element of the parameter array, to the value of the Box object array as the corresponding element.
I wrote a sample main method to test, but when I try to get the value of a particular element of a Box in the BoxList array, I get the NullPointerException. Can anyone offer advice to help trouble shoot this.
(These are snips of a larger program...I already wrote so much that I didn't want to clog further)
public class BoxList {
private Box[] boxArray;
public BoxList(double[] monetaryAmounts) {
Box[] boxArray = new Box[monetaryAmounts.length];
for (int i = 0; i < boxArray.length; i++) {
boxArray[i] = new Box(monetaryAmounts[i]);
}
}
public double getValue(int index) {
return boxArray[index].getValue();
}
// A sample main method to test out various object methods
public static void main(String[] args) {
double[] monetaryAmounts = {.5, 1, 3, 7.5, 8, 10}; // test array
BoxList test = new BoxList(monetaryAmounts);
System.out.println(test.getValue(0));
}
You initialized your boxArray properly, but you initialized a local variable boxArray, and your instance variable boxArray was unreferenced, so Java initialized it to null, causing the exception. Change
Box[] boxArray = new Box[monetaryAmounts.length];
to
boxArray = new Box[monetaryAmounts.length];
Related
Situation (new in java):
I would like to store random values into an array of objects of a class i created.
I created the following class:
private double color;
private double size;
// default constructor
public Example() {
color = 0.0;
size = 0.0;
}
// second constructor taking two arguments
public Example(double color, size imaginary){
this.color=color;
this.size=size;
}
// mutators
public void setColor(double c){
color=c;
}
public void setSize(double s){
size=s;
}
Now in my driver class:
I created the following
import java.lang.Math;
int num = 4;
Example[] array;
array = new Example[num];
for(int i=0;i<num-2;i++)
{
randomColor = Math.random();
randomSize = Math.random();
array[i].setColor(randomColor);
array[i].setSize(randomSie);
}
When i run the program i get the following error message:
Exception in thread "main" java.lang.NullPointerException
Im assuming that the content in each element of the array is null. But why is that? and how do i make the logic above work ?
Obviously i want to stay within the boundaries of my knowledge which is around the complexity of this code.
Thank you
You have only created an array of Example objects, but every element of it is null since you haven't created any Example object instances.
Arrays of "reference types" (anything that is a class, interface, enum or array, basically) start out with having null references in every element, and you still need to create the objects to put in the array.
Change your code to :
array[i] = new Example(randomColor, randomSize);
which will create new Example objects, and assign the random values to its properties.
I have a Java project where, in one class, an array is initialized, like so.
public class pixel {
public boolean[] pixelAvailability = new boolean[100];
}
In my main class, a method of another class I've created is run. The code for that method is as shown below.
public void walls() {
for (int i = 1; i <= 10; i++) {
// This is the part I need help with!
}
}
The intended use of this method is to change the value of some entries in the pixelAvailability array. In the space where the comment is, there's supposed to be a line that accesses the array, and will change the index of the array that has the same value of 'i' to true. However, I'm not sure what'd I'd write there, in order to change the value of the pixelAvailability array that exists in an instance of the pixel class that wasn't created in the "walls" class itself. The main class simply creates two instances of both classes, and is written like so.
public class main {
public static void main(String[] args) {
pixel pixelObj = new pixel();
wall wallObj = new wall();
walls();
}
}
While I could write the code for the "walls" method in the main method, it'd take up a lot of space and make it a bit messier, and seems unnecessary.
There is a fourth class unrelated to this particular problem, but will also have the issue of accessing the values in the pixelAvailability array. Any helps or tips are much appreciated!
You need to pass the Pixel object as an argument, first change your wall method to receive a Pixel as param
public void walls(Pixel pixel) {
for (int i = 1; i >= 10; i++) {
// here you can do whatever you want like pixel.pixelAvailability[i] = false;
}
}
then in your main, you pass the Pixel as a param
public class main {
public static void main(String[] args) {
pixel pixelObj = new pixel();
wall wallObj = new wall();
walls(pixelObj); //here you do the magic
}
}
Basically, you are changing your walls method to accept a Pixel instance as param. So you can access it inside your method.
Now, whenever you call the walls method you can pass any Pixel object to it.
For more info, you can check this link
https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
So I'm having a problem with passing values to another class in java.
I have an application which accepts an equation from the user, after the button gets clicked, it finds out the number of variables the equation has and I'm putting the variables in two lists. Now, I need to pass these variables to another class.
here's the snippet of code where I need to use the variables:
beeColony.java
public class beeColony {
int D;
double Foods[][]=new double[FoodNumber][D];
public void getDimension(int D)
{
this.D = D;
}
}
based from here, I need to initialize the variable Foods into having a size depending on the FoodNumber and D. There's no problem w/ regards to the FoodNumber since it is a static one.
in my main application there is an event handler
private void getvalueMouseClicked(java.awt.event.MouseEvent evt) {
bee.getDimension(dim);
}
when I output the variable D in one of my methods, it is equal to the value that I assigned it to. My problem is that the size of array Foods. I get an IndexOutOfBounds Exception. I think that when I initialize the array Foods, it is unable to get the value of D.
Any thoughts on how to fix this?
Why are you using getDimension() to set a value?
The reason this is happening is because you must have created a new class of beeColony and while doing that you used the default value of D (set to zero). It would then use this value of D to create the Foods array. This would create a Foods array of size FoodNumber x 0
I would change it as follows:
public class beeColony {
int D;
double Foods[][]=null;
public void getDimension(int D)
{
this.D = D;
this.Foods = new double[FoodNumber][D];
}
}
}
public void changeColor(int[] value)
{
color = value;
}
In the above code Color is a is a int Array in a class. and value is a array in the scope of method ChangeColor. By Color = value; I am assigning the memory space allocated to value to Color. As per my understanding once a method ended the variable specific to the method will be deleted, in that case will Color be able to access its value after the method ends??
"will Color be able to access its value after the method ends??"
Short answer: Yes, otherwise why would you define a variable as global.(No matter it's a reference or primitive)
Please run this code to see what happens:
public class Test {
int[] Color = new int[2];
int i = 20;
public static void main(String[] args) {
Test t = new Test();
t.ChangeColor(new int[] {1,2,3});
System.out.println(Arrays.toString(t.Color));
System.out.print(t.i);
}
public void ChangeColor(int[] value)
{
Color = value;
i = 10;
}
}
the int[] value parameter of the method is a reference to an array, but not a copy of the full array. Color is also a reference, so when you assign them, you make them point to the same array.
when the method exists, value is deleted from memory, but that was just a reference, not the array. So color which is still pointing to the array, will still be able to access even if the method has finished.
I'm doing a task for a course in Java programming and I'm not sure how the following thing is working? The method below takes the value from an array and a integer. The integer should be added to the array and then be used outside the method in other methods and so on, but how could this work when the method has no return for the new content of the array? There is a void in the method? Have I missed something? Preciate some help? Is there something about pointers?
public static void makeTransaction(int[] trans, int amount);
Arrays in Java are objects. If you modify the trans array inside the method, the changes will be reflected outside of it1. Eg:
public static void modify(int[] arr)
{
arr[0] = 10;
}
public static void main(...)
{
int x = {1, 2, 3};
System.out.println(x[0]); // prints 1
modify(x);
System.out.println(x[0]); // now it prints 10
}
Note that native arrays can't be dynamically resized in Java. You will have to use something like ArrayList if you need to do that. Alternatively you can change the return type to int[] and return a new array with the new element "appended" to the old array:
public static int[] makeTransaction(int[] trans, int amount)
{
int[] new_trans = Arrays.copyOf(trans, trans.length + 1);
new_trans[trans.length] = amount;
return new_trans;
}
1 It is also worth noting that as objects, array references are passed by value, so the following code has no effect whatsoever outside of the method:
public void no_change(int[] arr)
{
arr = new int[arr.length];
}
You can't add anything to an array. Java arrays have a fixed length. So indeed, what you want to do is impossible. You might make the method return an int[] array, but it would be a whole new array, containing all the elements of the initial one + the amount passed as argument.
If you want to add something to an array-like structure, use an ArrayList<Integer>.
Do you have to keep the method signature as is?
Also, can you be a bit more specific. When you say "the integer should be added to the array", are you referring to the amount argument? If so, then how is that amount added? Do we place it somewhere in the array or is it placed at the end, thus extending the array's length?
As far as pointers go, Java's pointers are implicit, so if you don't have a strong enough knowledge of the language, then it might not be so clear to you. Anyways, I believe that Java methods usually will pass objects by reference, and primitives by value. But, even that isn't entirely true. If you were to assign your object argument to new object, when the method terminates, the variable that you passed to the method is the same after the method executed as it was before. But, if you were to change the argument's member attributes, then when the method terminated those attributes values will be the same as they were inside of the method.
Anyways, back to your question, I believe that will work because an array is an object. So, if you were to do the following:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
}
// static int i;
/**
* #param args
*/
public static void main(String[] args)
{
int[] trans = {0,1,3};
makeTransaction(trans, 10);
for(int i = 0; i<trans.length; i++)
{
System.out.println(trans[i]);
}
}
The output of the array will be:
10
1
3
But, watch this. What if I decided to implement makeTransaction like so:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
trans = new int[3];
}
What do you think that the output will be? Will it be set to all zero's or will be the same as it was before? The answer is that the output will be the same as it was before. This ties in to what I was saying earlier.
I might've assigned that pointer to a new object in memory, but your copy of the pointer inside of the main method remains the same. It still points to the same place in memory as it did before. When the makeTransaction method terminates, the new int[3] object that I created inside of it is available for garbage collection. The original array remains intact. So, when people say that Java passes objects by reference, it's really more like passing objects' references by value.