在字符串后输入整数时出现InputMismatchException

问题描述 投票:0回答:1

我尝试在两年后修改java,并在字符串后输入整数时陷入此错误。 这是代码(yob 是出生年份,用户类别在另一个文件中定义):

import java.util.Scanner;


public class Main {
    public static void main(String[] args) {
        Scanner inputter = new Scanner(System.in);
        String name, email;
        int yob;
        
        User users[] = new User[5];
        for(int i = 0; i < 5; i++) {
            
            System.out.print("Enter your name: ");
            name = inputter.next()
            System.out.print("Which year were you born in? ");
            yob = inputter.nextInt();
            System.out.print("What's your email address? ");
            email = inputter.nextLine();
            users[i] = new User(name, yob, email);
            // To keep spacing between two sets of user input
            System.out.println(); 
            System.out.println();
        }
        
        System.out.println(users);
        inputter.close();

    }
}

还有错误: enter image description here

java string exception java.util.scanner user-input
1个回答
1
投票

inputter.next()
从扫描仪中读取“John”。
inputter.nextInt()
尝试将“Doe”读取为整数,但事实并非如此。

要修复,您可以将

inputter.next()
替换为
inputter.nextLine()

© www.soinside.com 2019 - 2024. All rights reserved.