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];
}
}
}
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.
public class foo {
private int a[];
private int b;
public foo(){
a = new int[] {1,2};
b= 3;
}
public int[] getA(){
return this.a;
}
public int getB(){
return this.b;
}
I noticed that it's possible to change a value of A by accessing the object like this:
foo f = new foo();
f.getA()[0] = 5; // f.a[0] changes to 5
but it isn't possible to do something like:
f.getB = 5; // gives error
f.getA() = new int[]{2,3}; //gives error
can someone explain me how this works, and how to prevent the user from changing the value of an array cell?
Thanks in advance.
In Java, array is a reference type, which means that the value of an array expression is a reference to the actual array.
The return value of getA() is, therefore, a reference to the private array inside your object. This breaks encapsulation: you give access to your object's internals.
You can avoid this by either returning a reference to a copy of your internal array, or by providing a different API which only returns individual elements, say a method getA(int index).
f.get(A) returns a reference to an array. You can access that array the way you access any array, and assign values to its elements with f.get(A)[i]=... (though it makes more sense to store the returned array in a variable, which would let you access that array multiple times, without having to call f.get(A) each time).
You can't, however, assign anything f.get(A) via f.get(A)=.., since a method call is not a valid left side of an assignment operator. For all you know, a call to f.get(A) may generate a new array that is not referred to by a member of the foo class, so assigning f.get(A)= new int[5]; would make no sense, since there would be no variable in which to store the new array.
The same explanation applies to f.getB() = 5;.
Instead of giving away the array, to allow the caller to do what they like with it you can use an indexed getter
public int getA(int n){
return this.a[n];
}
public void setA(int n, int x) {
this.a[n] = x;
}
Now, the caller has no access to the array and cannot change it without you knowing.
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 am trying to create a instance of the object Iset. When the person makes the object they have to give an int which will be the size of a boolean array that will store a set of integers e.g 1 will be Iset[1] = true etc etc. But I keep getting index out of range error. The rest of the program is obviously ignoring the values I set in the constructor so how do I make sure that the values I use in the constructor are used in all of my methods?
First part of the code:
public class Iset {
public int size;
boolean[] Iset;
ISet(int a) {
int size = a;
seti = new boolean[size];
Lets have a look at your code :
public class Iset {
public int size;// Declares a Member of a class and all the objects will have a copy of this member
boolean[] Iset;
.....
}
ISet(int a) {
int size = a; //This line is declaring a **local variable** called size
seti = new boolean[size];
...
}
See in your constructor you've created a local variable size but you also have a class member called size in your class. So in this scenario whenever we try to set size variable within constructor, there arises a conflict to the compiler whether to set the local variable or the class member ( this conflict is because of the fact that both the local variable and class member has same name ) . In such scenarios the compiler chooses local variable size over the class member size. But for you to make sure that the values you use in the constructor are used in all of my methods, you have to set the class member. To set the class member we use following code:
this.size = a;//Says set the object member size to value present in a.
Here we refer the size using this pointer because we need to set the object's size variable and not the local variable size.
You are creating a new variable inside your constructor and this is called shadowing. Use this to set the attributes of the current object:
this.size = a;
You're creating a new int variable inside the constructor. Instead, you just need to do this.size = a; in the constructor.
Try this:
public class Iset {
public int size;
boolean[] seti;
ISet(int a) {
this.size = a; // This will make methods access the value
this.seti = new boolean[size];
size variable in your constructor is a local variable, that's why other member methods doesn't get the right size to check.
Assign the value to this.size, then it will work:
ISet(int a) {
this.size = a;
seti = new boolean[size];
You should use the this keyword, an make the constructor public if you want to instantiate it in another class:
public class ISet {
public int size;
boolean[] iSet;
public ISet(int a) {
this.size = a;
this.iSet = new boolean[a];
}
You are not initializing the size instance variable properly, instead you are initializing a local variable size. Therefore your size instance variable remained initialized with 0 and your seti instance variable is an empty array causing the out of range error.
As pointed out by others, you don't need the instance variable size.
There is also no need for another local variable size inside your constructor, Just use seti.length to determine the size of the array. To simplify, your code should be:
public class Iset {
boolean[] seti;
ISet(int a) {
seti = new boolean[a];
I would recommend you use static analysis tools like checkstyle to eliminate bug like this in your codes.
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.