Help with Java array! basic question

HardTech

Golden Member
Oct 9, 1999
1,203
0
76
I'm creating an assignment in Java and I've instantiated an array with length of 69 (I didn't mean for it to be that number, it just happened to be it)

anyway, I HARD-CODED the values of all the values in the array. The array is made up of a class I made up called Currency, which has 4 values. Two strings, symbol and name, and two doubles, fromDollar and toDollar

I have 69 x 4 lines of code dedicated to hardcoding the values into the array. I did it like this:

Currency[] change = new Currency[69];

change[0].symbol = "DZD";
change[1].symbol = "USD";
change[2].symbol = "AUD"; and so on and so forth

but at the end, if I put in a for loop that reads:

for (int i = 0; i < change.length; i++) {
System.out.println(change.symbol);
}

I get the very last value 69 times. change[0].symbol is "ZWD" and change[68].symbol is also "ZWD"
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
Originally posted by: HardTech
I'm creating an assignment in Java and I've instantiated an array with length of 69 (I didn't mean for it to be that number, it just happened to be it)

anyway, I HARD-CODED the values of all the values in the array. The array is made up of a class I made up called Currency, which has 4 values. Two strings, symbol and name, and two doubles, fromDollar and toDollar

I have 69 x 4 lines of code dedicated to hardcoding the values into the array. I did it like this:

Currency[] change = new Currency[69];

change[0].symbol = "DZD";
change[1].symbol = "USD";
change[2].symbol = "AUD"; and so on and so forth

but at the end, if I put in a for loop that reads:

for (int i = 0; i < change.length; i++) {
System.out.println(change.symbol);
}

I get the very last value 69 times. change[0].symbol is "ZWD" and change[68].symbol is also "ZWD"

10-to-1 odds say the error is in the Currency class. Possibly incorrectly declaring symbol as a static field.

**Edit**
I'll bump that up to 1000-to-1, since I see no use of a Currency constructor to create any actual objects.

You need to do something like:
change[0] = new Currency("DZD");
change[1] = new Currency("USD");

Of course for that to work you need to have a constructor that creates a string and assigns that string value to a non-static symbol field.
 

HardTech

Golden Member
Oct 9, 1999
1,203
0
76
so I actually need a constructor?

I can't just do what I did? that sucks

back to doing busywork
 

clamum

Lifer
Feb 13, 2003
26,256
406
126
Yeah you would need to create a new Currency object to put into each position in the array.

Either do something like this:
change[0] = new Currency();
change[0].symbol = "DZD";

or this:
change[0] = new Currency("DZD");

For the second way, you would need a constructor that accepts a String and assigns the string to the symbol variable, like Kilrsat said above.