This site requires JavaScript, please enable it in your browser!
Greenfoot back
2woodsway
2woodsway wrote ...

2011/11/12

Please help desperate array question

2woodsway 2woodsway

2011/11/12

#
Declare an ArrayList named taxRates of   five  elements of type Double and initialize the elements (starting with the first) to the values 0.10 , 0.15 , 0.21 , 0.28 , 0.31 , respectively. I tried: double taxRates = {0.10, 0.15, 0.21, 0.28, 0.31}; and that returned incorrect
bourne bourne

2011/11/12

#
Try: ArrayList<Double> taxRates = new ArrayList<Double>(){{ add(0.1); add(0.15); add(0.21); add(0.28); add(0.31); }};
2woodsway 2woodsway

2011/11/12

#
That worked, thanks so much, if you have a moment can you explain? It worked , but I don't understand. I am a newbie newbie
bourne bourne

2011/11/12

#
An ArrayList is different from an array. It doesn't have to have a specific size determined when created. It's similar in the fact that it must have some type declared for what the elements it contains can be (in this case Double). The syntax differs: ArrayList<Double> taxRates = new ArrayList<Double>(); is "equivalent" to: Double taxRates = new Double; I used a "trick" with keeping it all in the same line but normally you would do the following to add elements: ArrayList<Double> taxRates = new ArrayList<Double>(); taxRates.add(0.1); taxRates.add(0.15); .. Furthermore they both give you access to their elements given some index from 0 to (size - 1). ArrayList<Double> taxRates = new ArrayList<Double>(); taxRates.get(0); is "equivalent" to: Double taxRates = new Double; taxRates; Hope that helps.
danpost danpost

2011/11/12

#
2woodsway wrote...
double taxRates = {0.10, 0.15, 0.21, 0.28, 0.31};
It probably would have worked with
double[] taxRates = {0.10, 0.15, 0,21, 0.28, 0.31};
You need to login to post a reply.