0

这一行:

arr[i] = sc.nextDouble();

从此代码:

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"); 
    } 
  } 
}

给出这个警告:

Type mismatch: cannot convert from double to int 

如何使 java 中的用户输入为 double 类型?

4

3 回答 3

3

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

于 2012-08-05T22:53:18.627 回答
0

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.

于 2012-08-05T22:54:30.297 回答
0

我注意到您的代码中有以下错误:

  • 当您double i在数组索引中读取int n. 这就是您的类型不匹配错误的来源。由于数组索引必须是 type int,因此arr[i]您尝试传递arr[double]arr[int]支持 where 的位置。

  • 如果您希望使用新的最小值重新分配它,则需要从开始,除非您输入的所有值都是负数minDouble.MAX_VALUE一定要相应地改变你的if (min != 0) {

于 2012-08-06T10:33:09.867 回答