Gregg1989
Gregg1989

Reputation: 695

InputMismatchException in Java

I am getting a InputMismatchException error, although everything should be working as intended. I only get the error when the user has to enter an int value (setAge). Why?

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);

    Withdraw myAccount = new Withdraw();

    Customer Jack = new Customer();
    out.println("Enter your full name");
    String FullName = keyboard.next();
    Jack.setName(FullName);

    out.println("Enter your address");
    String Address = keyboard.next();
    Jack.setAddress(Address);

    // I GET THE ERROR IN THE LINES BELOW.
    out.println("Enter your age");
    int age = keyboard.nextInt();
    Jack.setAge(age);

Here's the code for the Customer class

public class Customer {

String name;
String address;
int age;

public void setName(String NameIn) {
    name = NameIn;
}

public String getName() {
    return name;
}

public void setAddress(String addressIn) {
    address = addressIn;
}

public String getAddress() {
    return address;
}

public void setAge(int ageIn) {
    age = ageIn;
}

public int getAge() {
    return age;
}

Thanks in advance everyone!

Upvotes: 0

Views: 126

Answers (2)

rzymek
rzymek

Reputation: 9281

After reading the whole line as Reimeus suggested, you can parse the String to a int using

int age = Integer.parseInt(line);

Upvotes: 0

Reimeus
Reimeus

Reputation: 159754

By default, next uses whitespaces as word delimiters so any addresses containing these characters will cause the input to be passed through to the next Scanner input statement, namely nextInt in this case.

Therefore use nextLine which reads the entire line input:

String address = keyboard.nextLine();

The same will be required for fullName should any whitespaces exist in that variable.

Aside: Java naming conventions show that variables start with lowercase letters, e.g. address and fullName.

Upvotes: 2

Related Questions