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.
Related
I am wanting to make a method that can take in an array of n dimensions and then do some sorting with that info. The sorting part is out of the scope of this question though since the part I am stuck on is making a method accept an array of n dimensions. Normally you include something like int[] nums as a parameter. However, this does not allow for a scalable dimensional input. I did some research and the following code accurately calculates the dimensions of an array but I am not sure where to go from there since I cant figure out how to initialize an array of n dimensions from just an Object.
public static int dimensionOf(Object arr) {
int dimensionCount = 0;
Class<?> c = arr.getClass(); // getting the runtime class of an object
while (c.isArray()) { // check whether the object is an array
c = c.getComponentType(); // returns the class denoting the component type of the array
dimensionCount++;
}
return dimensionCount;
}
Here is something else to explain my issue lets say someone passes in a 2 dimensional array as the object. If that happened my dimensions variable would be equal to 2 since its using the above code to determine the dimension of the array. The thing I am stuck on is figuring out how to then produce a useable variable. Here you can see I tried to cast the object (which I know is an instance of array) to a 1d array which would through an error since the incoming object is a 2d array.
public static int sortNDimensionalArray(Object obj) {
int dimensions = dimensionOf(obj);
//This means we did not get an array passed in
if(dimensions == 0) return -1;
int[] array = (int[]) obj;
return 1;
}
I tried it out and got this and it works for me:
public static int dimensionOf(Object... args) {
int dim = 0;
Class<?> c = args.getClass();
while(c.isArray()) {
c = c.getComponentType();
dim++;
}
return dim;
}
I would like to have a static array in a Java class with an undetermined size initially. The intent is to use the array to store values calculated in a method in one class and used in another.
E.g. the 'TwoDX(Y)Pos[] arrays defined here:
public class DisplayObject {
// Each object is defined by a color, number of vertices, and dim (2,3,4) coordinate vertex locations
// Use dim to verify that the right number of vertices were sent
public static int Dim=3;
public static int RefDist=100;
public static int TwoDXpos[];
public static int TwoDYpos[];
}
And used here:
public void render2D(){
for (int cnt=0; cnt<this.NoOfVerts; cnt++){
if (this.coords[cnt*Dim+2] < RefDist) {break;}
TwoDXpos[cnt]=this.coords[cnt*Dim]/(this.coords[cnt*Dim+2]/RefDist);
TwoDYpos[cnt]=this.coords[cnt*Dim+1]/(this.coords[cnt*Dim+2]/RefDist);
}
}
But, since the original static references have no defined size, they reference Null pointers at execution.
How would you create such arrays?
I would like to have a static array in a java class with an initially undetermined size.
Sorry.
That isn't possible in Java. JLS-10.3. Array Creation says (in part)
The array's length is available as a final instance variable length.
Alternative
However, you could have a List of Foo(s) like
List<Foo> al = new ArrayList<>();
Use ArrayList instead of arrays.
Your code should look like this:
public class DisplayObject {
// Each object is defined by a color, number of vertices, and dim (2,3,4) coordinate vertex locations
// Use dim to verify that the right number of vertices were sent
public static int Dim=3;
public static int RefDist=100;
public static ArrayList<Integer> TwoDXPos;
public static ArrayList<Integer> TwoDYPos;
}
and the render 2d method:
public void render2D(){
for (int cnt=0; cnt<this.NoOfVerts; cnt++){
if (this.coords[cnt*Dim+2] < RefDist) {break;}
TwoDXpos.get(cnt)=this.coords[cnt*Dim]/(this.coords[cnt*Dim+2]/RefDist);
TwoDYpos.get(cnt)=this.coords[cnt*Dim+1]/(this.coords[cnt*Dim+2]/RefDist);
}
}
The advantage of using ArrayList is that you can use its add(item) method to change its size dynamically.
Hope it helps!
public void render2D() {
TwoDXpos = new int[this.NoOfVerts];
TwoDYpos = new int[this.NoOfVerts];
for (int cnt = 0; cnt < this.NoOfVerts; cnt++) {
if (this.coords[cnt * Dim + 2] < RefDist) {
break;
}
TwoDXpos[cnt] = this.coords[cnt * Dim] / (this.coords[cnt * Dim + 2] / RefDist);
TwoDYpos[cnt] = this.coords[cnt * Dim + 1] / (this.coords[cnt * Dim + 2] / RefDist);
}
}
and pls following Java naming rules to name your variable: http://www.iwombat.com/standards/JavaStyleGuide.html#Attribute%20and%20Local%20Variable%20Names
Short answer is you need to initialize the array before using them.
To avoid memory leakage, you should set its size at initialization. e.g.10.
public static int TwoDXpos[] = new int[10];
public static int TwoDYpos[] = new int[10];
If the array size changes, you should use ArrayList because its size is automatically managed by JVM
You can't use an array whose size is not determined. You should initialize the array size before method render2D() called. May be you could use this.NoOfVerts as the array size.
If you are going to use an array, you should initialize it by mentioning the size of the array in order to allocate memory before using it.
public static int TwoDXpos[];
public static int TwoDYpos[];
Any access on this would throw NullPointerException because the memory for this not allocated and object defintion has not happened at all.
You ought to remember this on array (or any objects for that sake) "Initialize before you access/use them"
If you worry is about that you are not sure about the number of elements upfront, you should use utilities like ArrayList which is provided in Java Collection Framework. This would take care dynamically adjusting the size as the number of elements increases.
Alternative Approach
private static List<Integer> twoDXPos = new ArrayList<Integer>();
private static List<Integer> twoDYPos = new ArrayList<Integer>();
and then itemes can be added using add method in java.util.Collection class. (Refer the link I gave above)
twoDXPos.add(1) //1 is an example integer here to illustrate
twoDYPos.add(1) //1 is an example integer here to illustrate
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];
}
}
}
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];
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.