Reputation:
I am getting the error
"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)"
when I have this code running. Can anyone tell me what I am doing wrong?
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;
}
}
Upvotes: 0
Views: 323
Reputation: 1115
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.
Take a look at this answer: https://stackoverflow.com/a/14027583/7421645 and try understand why you are getting the exception, e.g. try to catch the exception:
try {
// ...
} catch (InputMismatchException e) {
System.out.print(e.getMessage()); //try to find out specific reason.
}
I'd also try inputting the test data as a String
first, at least until you are sure that your expected inputs provides the expected outputs.
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
Upvotes: 1