Issue
I am trying to traverse an array in Java via a for loop, but for some reason it will only print the doubles in my list if I cast 'int'. Otherwise I get a "Type Mismatch: cannot convert double to int" even though everything is a double and I never once attempt to convert any number to an int. I am a complete begginer to programming, so any and all help is greatly appreciated. Here is the code:
package MyProgram1;
import cs1.Keyboard;
public class MyProgram1{
public static void main(String[] args){
double [] array = {1.0,2.0,4.0,2.5,5.0};
for (double index = 0.0; index <= array.length-1.0; index++){
\\The line below is what results in the error
System.out.println(array[index]);
}
}
}
I saw a suggestion (in eclipse) that said "add cast to int" and here is what that looks like:
package MyProgram1;
import cs1.Keyboard;
public class MyProgram1{
public static void main(String[] args){
double [] array1 = {1.0,2.0,4.0,2.5,5.0};
for (double index = 0.0; index <= array1.length-1.0; index++)
System.out.println(array1[(int)index]);
}
}
Works perfectly and what prints is the following:
1.0
2.0
4.0
2.5
5.0
My question is why? Why do I need to cast it, and when I do, why is everything printed as a double? Shouldn't the results be integers?
Again, any clarification is appreciated.
Solution
The problem is that you are iterating over your array with "double" variable. Array indices are of integer type
Change your "index" variable type to int and it should be fine i.e.,
public static void main(String[] args){
double [] array = {1.0,2.0,4.0,2.5,5.0};
for (int index = 0; index <= array.length-1; index++){
System.out.println(array[index]);
}
}
There are other ways to iterate over array as well. HEre is one where you don't need special index. rather you need a variable (of the same type as array) to hold the value i.e.,
for (double val : array) {
System.out.println(val);
}
Answered By - Em Ae
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.