Reputation: 1
This line:
arr[i] = sc.nextDouble();
from this code:
public class z01 {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size: ");
int n = sc.nextInt();
double[] arr = new double[n];
double min = 0;
for(double i = 0; i <n; i++){
System.out.println("Enter element " + (i + 1));
arr[i] = sc.nextDouble();
if(i%3 == 0 && i <= min){
min = i;
}
}
if(min != 0){
System.out.println("The smallest number divisible by 3 is" + min);
} else {
System.out.println("No number is divisible by 3");
}
}
}
Gives this warning:
Type mismatch: cannot convert from double to int
How do I make user input in java be of the type double?
Upvotes: 0
Views: 11694
Reputation: 3067
I noticed the following errors within your code:
You are using a double i
in your for-loop for being the array index, when you read in the array index to int n
. That's where your Type Mismatch error is coming from. As array indexes must be of the type int
, the arr[i]
you have is attempting to pass an arr[double]
where only arr[int]
is supported.
Your min
needs to start at Double.MAX_VALUE
if you want it to ever be re-assigned with the new minimum, unless you all entered values will be negative. Be sure to change your if (min != 0) {
accordingly.
Upvotes: 0
Reputation: 1244
Your problem here is probably that the array arr is of type int. That is why you get that error. Define arr as follows and try again (where x the desired dimension):
double arr[] = new double[x];
The problem is that you have set i
in the for loop to be of type double
while it should be of type int
Upvotes: 3
Reputation: 789
One method is to use a try catch exception.
try {
double var = sc.nextDouble();
}
catch(TypeMismatchException ex) {
System.err.println("try again, wrong type");
}
basically, if there is an error storing the value in a double, it'll execute the catch statement, and you can prompt the user again for more input.
Upvotes: 0