Okay, let me be more specific on what is happening. The code through each iteration of the for loop runs fine in that, code not included here, inputs are taken in from a user which are stored in the "Ball" object which is then stored in ballStorage. I have a to print in the for loop to show me what the "Ball" object at ballStorage[i] contains and the results are accurate. However, when I print out the results of the entire array's content after the for loop, every single "Ball" object in the array is overwritten with the last "Ball" object's values. I then checked to see what happens if I add a new "Ball "object outside of the for loop to ballStorage.length-1 which is empty and find that "Ball" object overwrote all the other "Ball" objects in the array. Please help and sorry for not being clear about what is happening.
for(int i = 0; i < ballStorage.length-1; i++){
ballStorage[i] = new Ball();
System.out.println("\n Ball number "+i+": \n"+ballStorage[i].toString());
}
if you want an array that store objects do this:
class Ball {
public static void main (String[] args) {
Ball[]obj =new Ball[5];
for(int i=0;i<5;i++)
{
obj[i]=new Ball();
}
for(int i=0;i<5;i++)
{
System.out.println(obj[i]);
}
}
}
I didn't much gets your question. But you can access the object of an array inside the loop by index after assigning its new object. let say
for(int x=0; x<ballStorage.Length; x++){
ballStorage[x] = new Ball(x); //assign value of the ball inside constructor
//access the ball
ballStorage[x].bounce(); //example
// or you can do this, access previous ball
if(x > 0)
ballStorage[x-1].bounce();
}
Related
I put a partial of my code which I think is the source of problem but I could not figure out hence why I am at StackOverFlow now. Anyways this Class is where i set my data and pass it into an array.
public ArrayList<select.rates> caseGetRates() throws RateTableException, SessionDisconnectedException {
try {
for(int i=0;i < arrayRate.size();i++){
ArrayList<select.rates> arr = new ArrayList<select.rates>();
this.setPair(array[0]);
this.setBid((array[2]));
this.setAsk((array[3]));
arr.add(this);
}
return arr;
} finally{}
}
When I System.out.print the data which I set in this class it gives me:
EUR/USD
1.12372
1.12384
USD/JPY
100.622
100.641
which is correct and what I would like it to be displayed on my webpage.However when I pass the data to my Servlet
try {
ArrayList<select.rates> rates = example.caseGetRates();
for(int i=0;i < rates.size();i++){
System.out.println("");
System.out.println(rates.get(i).getPair());
System.out.println(rates.get(i).getBid());
System.out.println(rates.get(i).getAsk());
}
request.setAttribute("rates", rates);
}
request.getRequestDispatcher("/NewFile.jsp").forward(request, response);
The result I get on my Servlet is:
USD/JPY
100.622
100.641
USD/JPY
100.622
100.641
The result does loop twice however the data seems to be overwritten and I still can't figure out why is this happening. I hope someone can pin point my mistake.
Create ArrayList object outside for loop
and inside for loop create new Object that you are adding to ArrayList
try {
ArrayList<select.rates> rates = example.caseGetRates();
for(int i=0;i < rates.size();i++){
// create new object here and then add to ArrayList
}
request.setAttribute("rates", rates);
}
request.getRequestDispatcher("/NewFile.jsp").forward(request, response);
I'm trying to make a booking system for a hotel using the MVC dp. I have a class with a fixed arraylist of rooms (from 1-25) inside the model and class in which I have the showAvailableRooms method in the controller package . I'm asking my View to print out the available rooms but the only thing it prints out is two square brackets ([]).
P.S. The get OccupiedRoom is another method I have in my bookinglist class (model). It checks if the dates you pass it as arguments are a problem to already existing bookings,if it is then it checks if the room is already in that occupied list and if it isn't it adds it to the list.
public void showAvailableRooms(MyDate arrivaldate, MyDate departuredate) {
ArrayList<Room> availablerooms = new ArrayList<Room>();
for (int i = 0; i < 25; i++) {
for (int j = 0; j < l.getOccupiedRoom(arrivaldate, departuredate).size(); j++) {
if (h.getRoom(i) != l.getOccupiedRoom(arrivaldate, departuredate).get(j)) {
availablerooms.add(h.getRoom(i));
} else if (l.getOccupiedRoom(arrivaldate, departuredate).size() == 0) {
System.out.println(h.getAllRooms());
}
}
System.out.println(availablerooms);
}
As i said in comment [] means your list is empty.
you add elements to availablerooms only in your inner loop, but if l.getOccupiedRoom returns you empty list, then code inside inner loop won't be executed, and no empty rooms will be added.
two square brackets ([]). Means that availablerooms doesn't have any entry. Either there are no available rooms, or it isn't getting populated correctly. Please check your logic.
i have short question, tell me just why first example don't work and second works.
Code before examples:
Tiles[] myTiles = new Tile[23];
number = 1;
First Example:
for(Tile tile : this.myTiles) {
if (number != this.myTiles.length) {
tile = new Tile(number, getResources().getColor(R.color.puzzle_default));
number++;
}
}
Second Example:
for(Tile tile : this.myTiles) {
if (number != this.myTiles.length){
this.myTiles[number-1] = new Tile(number, getResources().getColor(R.color.puzzle_default));
number++;
}
}
If i use code below in other method in class
this.myTiles[0].getNumber();
It's NullPointerException.
But with Second Example it nicely works.
I really don't know why. Thanks for any response
The first loop makes a copy of each object and is equivalent to
for (int i=0; i < myTiles.length; i++) {
Tile tile;
...
tile = new Tile(...); // set local reference only
}
As elements in an Object array are null by default these would remain unassigned outside the scope of the loop. The original elements of the myTiles remain at their default null values
The for each loop uses an Iterator internally to fetch items from the collection and return you a new reference to a local variable containing each element - overwriting this reference is completely useless, as it is only valid for one for-loop and will be replaced on the next.
"Internally", your first loop would translate to
for (Iterator<Tile> iterator = myTiles.iterator(); iterator.hasNext;){
Tile tile = iterator.next();
tile = new Tile(number, getResources().getColor(R.color.puzzle_default));
number++;
}
In Java, there is no such thing as manipulating a pointer directly. Any time you get a reference to an object, you are getting a copy to a reference, like a pointer to a pointer. For this reason if you do something like:
String s = "hello";
modify(s);
System.out.println(s); // still hello!
void modify(String s){
s = s + " world";
}
You can't actually change the original reference s because the function is manipulating a copy to that reference. In the example above you would need something like this:
String s = "hello";
s = modify(s);
System.out.println(s); // prints 'hello world'
String modify(String s){
return s + " world";
}
The same happens in your for comprehension. The variable tile is bound to the loop and is a copy of a reference in the array. The original reference (the array at the given position) can't be changed directly this way. That's why you need to call directly:
myTiles[i] = // something
Read this article for more information.
So the idiomatic way of modifying an array in java is something like:
for(int i = 0; i < myTiles.length; i++){
myTiles[i] = new Tile(...); // directly reassigning the reference in the array!
}
Basically, I have an ArrayList of BudgetItem objects (BudgetItem being a class I made). Each BudgetItem has three instance variables, price, name, and quantity with setters and getters for each. I am adding each BudgetItem to the ArrayList one at a time, each with different information in the price variable. When I go to print out any price element of the ArrayList, using the get method, the console will always print the last price that was entered. Below, I will paste some sample code to help:
public class Register {
private ArrayList<BudgetItem> register = new ArrayList<BudgetItem>();
public Register(double[] price) {
//Creates a register ArrayList with specified number of
//elements and populates it with BudgetItems that contain
//the data in the price array entered in the declaration.
BudgetItem bi = new BudgetItem();
for(int i = 0; i<price.length; i++) {
bi.setPrice(price[i]);
register.add(bi);
if(i=0) { //This if statement is for debugging.
System.out.println(register.get(i).getPrice());
}
}
//This is also for debugging.
double i = register.get(0).getPrice();
System.out.println(i);
}
}
Through my debugging efforts I found that the problem is with the get method in ArrayList. No matter what I do it returns the last instance of price that was entered. My question is why won't the get method return the specified element?
Well the problem is that you always modify the same BudgetItem object.
Try :
for(int i = 0; i<price.length; i++) {
BudgetItem bi = new BudgetItem(); <-- move it inside the for loop
bi.setPrice(price[i]);
register.add(bi);
}
You are only adding a single BudgetItem and setting and resetting its price. You need to add new BudgetItems and set their prices accordingly.
Add BudgetItem bi = new BudgetItem(); inside for loop
I have a loop in which I calculate a value and add it it a list. So, I do something like that:
x = getValue()
values.add(x)
while (true) {
x = getValue();
values.add(x)
}
I found out that this approach does not work since I add the same instance to the list. In more details, in every cycle of the loop I re-assign a new value to the x and doing so I change values of all elements that were already added to the list (so in the end I get a list of identical elements).
To solve this problem I did the following:
x = getValue();
Integer[] valueToAdd = new Integer[n];
for (int i=0; i<n; i++) {
valueToAdd[i] = x[i];
}
while (true) {
x = getValue();
y = new Integer[n];
for (int i=0; i<n; i++) {
valueToAdd[i] = x[i];
}
values.add(valueToAdd)
}
In this way I wanted to create a new instance every time want to add a value to the list. But it does not work since I get a duplicate local variable error.
It is also strange to me that I do not have this error if I declare the same variable many times in the loop. The problem appears only if I first declare a new variable outside the loop and then also in the loop.
Is there a way in Java to re-use the same name for different instances?
ADDED
I need to clarify some issues. I did not show all the code. I have the break command in the loop (when a new value cannot be generate, I exit the loop). x and value have Integer[] type.
ADDED 2
Since it was mentioned that the problem can be in the getValue() I need to in more details here. Actually I do not have getValue() in my code (I used getValue() here to make my example shorter). In my code I had:
Integer[] x = new x[n];
while (true) {
for (int i=0; i<n; i++) {
x[i] = y[i];
}
values.add(x)
}
And it did not work since in my values list I had identical elements (and I know that in the loop on every cycle x had a new value).
ADDED 3
Why all elements of my list seems to be the same?
Your problem is not what you think it is. For example take a look at this simple program:
String x = null;
List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i ++) {
x = String.valueOf(i);
l.add(x);
}
System.out.println(l);
It prints the numbers from 0 to 9. This is because java is pass-by-value (check here). You are not passing the reference to x, you are passing the value of x (in the add method).
So the problem lies in the getValue() method, which returns the same object.
Update: Now the question makes more sense. You are working with the same object x everytime, and just changing its state. In order to put different values just move the declaration inside the loop:
while (true) {
Integer[] x = new x[n];
...
}
If you need it outside the loop, well, simply use another variable there. It does not have to be named x. Since you won't be using it inside the loop anyway.