I've got two problems. Please find my code attached below:
public class Numbers {
public static void main(String[] args) {
double[] tab = { 9.0, 27, 5, 77 };
System.out.println("array size: " + tab.length);
for (int y = 0; y < tab.length; y++) {
System.out.printf("%d", (int) tab[y]);
System.out.print(" ");
System.out.print(Math.sqrt(y));
System.out.println();
}
// for(double i:tab){
// System.out.println(tab[(int) i]);
// }
}
}
And now
1) my first problem is that I have some numbers in my array tab
and then in the FOR loop I want to display in each line the element and its square root.
But for the first element i get 0.0 as a square root. why? The other results are wrong as well to me.
my outcome:
array size: 4
9 0.0
27 1.0
5 1.4142135623730951
77 1.7320508075688772
2) second problem is with my for each loop which is commented. But when you uncomment it the it doesnt work because I get an error. The output:
array size: 4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
What did I do wrong with this for each loop? Why eclipse shows that I ask about 9-th element?
Thank you for help in advance - all answers are appreciated :)
But for the first element i get 0.0 as a square root. why?
Because you're not printing out the square root of the element - you're printing out the square root of the index. This:
System.out.print(Math.sqrt(y));
should be:
System.out.print(Math.sqrt(tab[y]));
See more on this question at Stackoverflow