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 的所有元素后,这段代码给我一个不寻常的错误。 错误是:- 在线程“main”中的 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)
最佳答案
你的程序告诉我们:
Enter elements of your array, input an alphabet in order to exit
然后只要输入了 int
就循环,然后停止但永远不会读取字母字符。
然后你的程序告诉我们
Enter a value which you wish to search in the array
并直接尝试从扫描仪读取一个int
int value = input.nextInt();
但输入的下一个仍然是字母字符,因为您从未阅读过它,因此 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.
现在如何解决这个问题?
当您退出第一个阅读循环以跳过字母字符时,您可以简单地添加对 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();
关于java - 尝试读取 int 时出现 InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31761990/