每次在扫描仪中键入人员姓名时,我总是出现 InputMismatchException 错误?

I keep having InputMismatchException error every time I type the name of the person in the Scanner?

提问人:Vincent 提问时间:8/4/2023 最后编辑:Vincent 更新时间:8/4/2023 访问量:31

问:

我的代码有什么问题,为什么每次在控制台中键入名称时都出现 InputMismatchException 错误?

Scanner sc = new Scanner(System.in);
        System.out.println("How many People are there ? (employee and students included)");

        int  numPeople = sc.nextInt();
        Person[] personArray = new Person[numPeople];
        Student[] studentsArray = new Student[numPeople];
        Employee[] employeesArray = new Employee[numPeople];

        int i=0;

        while(i < numPeople) {
            System.out.println("Please enter the name and age of the person");
            String name = sc.nextLine();
            int age = sc.nextInt();sc.nextLine();
            Person person = new Person(name, age);
            personArray[i] = person;
            i++;
java.util.scanner 输入MismatchException

评论

2赞 Mike 'Pomax' Kamermans 8/4/2023
请记住:如果收到错误,请显示整个错误。还要记住为您的代码显示最小的可重现示例,因为现在您的 while 循环甚至没有正确闭合,并且没有围绕它的公共主函数,也没有围绕它的类。最后,在提交帖子后查看您的帖子,然后对其进行编辑以修复缩进严重关闭之类的问题 =)
1赞 g00se 8/4/2023
猜测,因为我们有部分代码,但代替了 int age = sc.nextInt(); 尝试int age = sc.nextInt();sc.nextLine();
1赞 user207421 8/4/2023
使用此代码,您需要在单独的行中输入姓名和年龄。这就是你正在做的事情吗?这是本意吗?如果没有,请更改为 。String name = sc.nextLine();String name = sc.next();
0赞 Vincent 8/4/2023
感谢您的所有回答。所以完成错误是: 线程“main”中的异常 java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:947) at java.base/java.util.Scanner.next(Scanner.java:1602) at java.base/java.util.Scanner.nextByte(Scanner.java:2011) at java.base/java.util.Scanner.nextByte(Scanner.java:1965) at Main.main(Main.java:20)
1赞 user207421 8/4/2023
@OldDogProgrammer 不,它没有。再看一遍。

答: 暂无答案