尝试读取int时的InputMismatchException

时间:2015-08-01 12:45:47

标签: java java.util.scanner

import java.util.Collections;
import java.util.ArrayList;
import java.util.Scanner;

public class BinarySearch 
{
    public static void main(String [] args)
    {
        Scanner input = new Scanner(System.in);
        ArrayList <Integer> a = new ArrayList <Integer> ();
        System.out.println("Enter elements of your array, input an alphabet in order to exit");
        while(input.hasNextInt()) //takes input from the user until data type becomes something other than int
        {
            int i = input.nextInt();
            a.add(i);
        }
        Collections.sort(a); //Sorts the arrayList
        System.out.print("Enter a value which you wish to search in the array- ");
        int value = input.nextInt();
        System.out.println(contains(a,value));
    }




    public static String contains(ArrayList<Integer> a, int value) //Uses the binary search algorithm to search for an element in the arrayList
    {
        int low=0;
        int high=a.size()-1;
        while (low<=high)
        {
            int mid = (high + low)/2;
            if (value==a.get(mid))
            return value+" is present in the given array at   position "+(mid+1);
            else if(value<a.get(mid))
            high=mid-1;
            else
            low=mid+1;
        }
        return value+"is not present in the given array";
    }



}

输入arrayList的所有元素后,此代码给出了一个异常错误。 错误是: - 在thread&#34; main&#34;中输入您希望在arrayException中搜索的值。

java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at BinarySearch.main(BinarySearch.java:19)

1 个答案:

答案 0 :(得分:4)

您的计划告诉我们:

  

输入数组元素,输入字母表以退出

然后只要输入int就循环,然后停止但是从不读取字母字符。

然后你的程序告诉我们

  

输入您要在数组中搜索的值

并直接尝试从扫描仪中读取int

int value = input.nextInt();

但输入的下一个仍然是字母字符,因为你从未读过它InputMismatchException

关于异常的文档很清楚,因为:

  

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

现在该如何解决这个问题?

当您退出第一个阅读循环以跳过字母字符时,您可以简单地添加对input.next的调用:

while (input.hasNextInt()) {
    int i = input.nextInt();
    a.add(i);
}
input.next();
Collections.sort(a);
System.out.print("Enter a value which you wish to search in the array");
int value = input.nextInt();