0

我收到 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;
}

提前谢谢大家!

4

2 回答 2

2

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

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

String address = keyboard.nextLine();

fullName如果该变量中存在任何空格,则同样需要。

另外:Java 命名约定表明变量以小写字母开头,例如addressand fullName

于 2013-10-31T12:35:32.963 回答
0

按照 Reimeus 的建议阅读整行后,您可以将其解析Stringintusing

int age = Integer.parseInt(line);
于 2013-10-31T13:29:24.567 回答