. Advertisement .
..3..
. Advertisement .
..4..
This is the program I run:
import java.util.Scanner;
public class Sal {
public static void main (String args []){
Scanner s=new Scanner(System.in);
System.out.println("Enter 10 areas and their pincodes");
String area[]=new String [10];
int pincode[]=new int [10];
String search;
int chk=0;
int p=0;
for (int i=0;i<=9;i++){
area[i]=s.nextLine();
pincode[i]=s.nextInt();
}
System.out.println("Enter Search");
search=s.nextLine();
for (int j=0;j<=9;j++){
if(search==area[j]){
chk=1;
j=p;
break;
}
}
if(chk==1){
System.out.println("Search Found "+"Pincode : "+pincode[p] );
} else {
System.out.println("Search not Found");
}
}
}
After I run, it returns an error
Exception in thread "main" 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 Sal.main(Sal.java:14)
Does anyone have any suggestions for my problem: exception in thread “main” java.util.inputmismatchexception in the programs – How to correct it?
The cause: The input does not match the Integer regular expression, or is out of range. I guess that at some point, your call to
.nextLine()
swallows up an entire line, and the next line starts with an “area”.Solution:
Compare Strings with the compareTo method (which returns zero if they are equal)
The
Scanner#nextInt()
docs:It sounds like your
Scanner
has tried to read in aint
, but it is getting something it cannot turn into aint
(either the number it read isn’t readable or it is too large).This is the function you call:
I suspect that
.nextLine()
‘s call takes up a whole line. The next line begins with an “area”. Without knowing what format you want the input to look like, I can’t do much more.