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

时间:2017-02-20 22:16:44

标签: java arrays methods java.util.scanner inputmismatchexception

我收到错误

  

"线程中的异常" 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;
    } 
}

1 个答案:

答案 0 :(得分:1)

  

公共课InputMismatchException   由扫描程序抛出,表示检索到的令牌没有   匹配预期类型的​​模式,或者令牌不在   预期类型的​​范围。

请看一下这个答案:https://stackoverflow.com/a/14027583/7421645并尝试了解您获得例外的原因,例如试着捕捉异常:

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