# Array trouble

David Barry

Ranch Hand

Posts: 85

posted 7 years ago

Can I create an array that stores the values that are incremented here: "for ( x = 1 ; x >= -1 ; x-=0.1 ) System.out.println(x);". I need to do this because I need these numbers incremented here for another calculation. If I can't form an array out of them, then what can I do to get them so I can do calculations with each one. Thanks

posted 7 years ago

Sure you can. Create a double[] and in the loop body store the value of x inside the the appropriate position in the array. You will probably need another (int) counter that increments for each step in the loop.

Why store the values? Can you move the calculation that uses the value of x inside the body of the for loop?

Why store the values? Can you move the calculation that uses the value of x inside the body of the for loop?

Steve

David Barry

Ranch Hand

Posts: 85

posted 7 years ago

if you want to store the values in an array, you'd store them like any other value. you need to declare an array big enough to hold the values you want, then you just stick them in. You could do something like this:

gives this output:

C:\slop>java Tester

x is 1.0, y is 0.

x is 0.9, y is 1.

x is 0.79999995, y is 2.

x is 0.6999999, y is 3.

x is 0.5999999, y is 4.

x is 0.4999999, y is 5.

x is 0.39999992, y is 6.

x is 0.29999992, y is 7.

x is 0.19999993, y is 8.

x is 0.09999993, y is 9.

x is -7.301569E-8, y is 10.

x is -0.100000076, y is 11.

x is -0.20000008, y is 12.

x is -0.30000007, y is 13.

x is -0.40000007, y is 14.

x is -0.50000006, y is 15.

x is -0.6000001, y is 16.

x is -0.7000001, y is 17.

x is -0.80000013, y is 18.

x is -0.90000015, y is 19.

y here is your index of the array, and x is the value. This gets a little complicated if you need to remember what each position is... it's not very intuitive that array[17] would hold (approx.) -0.7

I am assuming you did not mean that you want to use the value of 0.9 as the index to your array.

gives this output:

C:\slop>java Tester

x is 1.0, y is 0.

x is 0.9, y is 1.

x is 0.79999995, y is 2.

x is 0.6999999, y is 3.

x is 0.5999999, y is 4.

x is 0.4999999, y is 5.

x is 0.39999992, y is 6.

x is 0.29999992, y is 7.

x is 0.19999993, y is 8.

x is 0.09999993, y is 9.

x is -7.301569E-8, y is 10.

x is -0.100000076, y is 11.

x is -0.20000008, y is 12.

x is -0.30000007, y is 13.

x is -0.40000007, y is 14.

x is -0.50000006, y is 15.

x is -0.6000001, y is 16.

x is -0.7000001, y is 17.

x is -0.80000013, y is 18.

x is -0.90000015, y is 19.

y here is your index of the array, and x is the value. This gets a little complicated if you need to remember what each position is... it's not very intuitive that array[17] would hold (approx.) -0.7

I am assuming you did not mean that you want to use the value of 0.9 as the index to your array.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors