java - 为什么我会收到此错误?(双数组方法)

标签 java arrays methods java.util.scanner inputmismatchexception

我收到错误

"Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119) at SearchArray.main(SearchArray.java:10)"

当我运行此代码时。谁能告诉我我做错了什么?

import java.util.Scanner;
public class SearchArray {
    public static void main (String args[]){
        //imput array size
        //imput array digits
        //imput element to search for

        Scanner scan = new Scanner(System.in);
        int size = scan.nextInt();
        double array[] = new double[size];

        for(int i = 0; i <= array.length-1; i++){
           array[i] = scan.nextDouble();
        }

        double digit = scan.nextDouble();
        boolean bool = findElement(array,digit);

        if(bool == true){
           System.out.println(digit + " was found in the array");
        }else if(bool == false){
           System.out.println(digit + " was NOT found in the array");
        }
    }

    public static boolean findElement(double[] array, double digit){
        boolean bool = false;
        //accepts double array, double  & returns boolean
        //check if numnber entered is in the array

        for(int i = 0; i <= array.length-1; i++){
            if(array[i] == digit){
               bool = true;
            }else{
               bool = false;
            }
        }

        return bool;
    } 
}

最佳答案

public class InputMismatchException Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

看看这个答案:https://stackoverflow.com/a/14027583/7421645并尝试理解为什么你会遇到异常,例如 try catch 异常:

try {
    // ...
} catch (InputMismatchException e) {
    System.out.print(e.getMessage()); //try to find out specific reason.
}

我还会尝试首先以 String 形式输入测试数据,至少直到您确定预期输入提供了预期输出为止。

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);

关于java - 为什么我会收到此错误?(双数组方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42355211/

相关文章:

java - 启动时线程崩溃的代码(android初学者)

java - MySQLNonTransientConnectionException : Client does not support authentication protocol requested by server; consider upgrading MySQL client

java - 为什么 Java 编译器不能从另一个文件中找到类?

java - 获取完整的字符串堆栈跟踪,包括内部异常

java.time.Period ,除以周期会给出错误的结果

javascript - 在嵌套数组中查找具有值的对象并添加属性

php - 将元素从一个数组移动到另一个数组

c - 输入到无符号字符数组

java - 在 AlertDialog 中调用方法时出错

c++ - 从另一个方法调用非静态成员方法