Java中的InputMismatchException

时间:2013-10-31 12:31:54

标签: java java.util.scanner

我收到一个InputMismatchException错误,尽管一切都应按预期工作。当用户必须输入int值(setAge)时,我才会收到错误。为什么呢?

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

以下是Customer类的代码

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

先谢谢大家!

2 个答案:

答案 0 :(得分:2)

默认情况下,next使用空格作为单词分隔符,因此包含这些字符的任何地址都会导致输入传递到下一个Scanner输入语句,即nextInt在这种情况下

因此使用nextLine读取整行输入:

String address = keyboard.nextLine();

如果该变量中存在任何空格,fullName将需要相同的内容。

除此之外:Java命名约定显示变量以小写字母开头,例如addressfullName

答案 1 :(得分:0)

在阅读Reimeus建议的整行后,您可以使用

String解析为int
int age = Integer.parseInt(line);