user2711784 user2711784 - 3 days ago 4
Java Question

Java Error "Exception in thread "main" java.util.InputMismatchException" On an Array program

I recently typed out this java program to accept ten areas and their pin-codes and then search to find a particular area and print out it's pin-code.
Here's the code from the program :

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


And after entering two areas I get this 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)


Can someone please tell me what I'm doing wrong! :/
Any help is appreciated.

Answer

First of all, remember to indent your code for readability.

Concept 1.

for (int i=0;i<=9;i++){

area[i]=s.next();// Use this for String Input

pincode[i]=s.nextInt();

s.nextLine();//Use this for going to next line of input

}

Concept 2.

if(search.compareTo(area[j])==0){ 

// compare Strings using compareTo method (which returns 0 if equal

Rest of your code and concepts are correct :)

Comments