Reputation: 25
import java.util.*;
public class Main {
public static void main(String[] args) {
double[] temp = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
double[] tripple = {26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
for (double value : temp) {
System.out.println(value);
}
for (int k = 26; k < 50; k++) {
tripple[k] = (int) Math.pow(temp[k], 3);
}
for (double value : tripple) {
System.out.println(value);
}
}
}
I have been trying to get my second array to give cubed numbers from 26 onwards. So far, I have the 1-25 working, but I can't get the last twenty five to work. I've tried everything I can think of, and what is there is the last iteration after hours of banging my head on the walls.
Upvotes: 0
Views: 61
Reputation: 117
Those are two different arrays. Both will start from 0. So you need to use following in second array.
for(int k=0;k<tripple.length;k++){}
This means
triple[0]=26;
and so on.
One more thing you have used temp array in the line below
tripple[k] = (int) Math.pow(temp[k], 3);
Here values in the temp array are different.
temp[0]=1;
temp[1]=4;
and so on
Upvotes: 0
Reputation: 727137
This loop is incorrect, because it uses values instead of indexes:
for (int k = 26; k < 50; k++) {
tripple[k] = (int) Math.pow(temp[k], 3);
}
When you apply operator [i]
to an array, it means "give me the element at position i
counting from zero". It does not mean "give me an element whose value is i
".
k
needs to be from zero to tripple.length()
, the same way the i
goes in your first for
loop.
Upvotes: 1
Reputation: 207026
The error is in this line:
for (int k = 26; k < 50; k++)
The indices in the array tripple
do not go from 26 to 50, but from 0 to the length of the array.
for (int k = 0; k < tripple.length; k++)
Upvotes: 1