0

what is the problem with my code and why do I have the InputMismatchException error every time I type the name in the console ?

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++;
8
  • 2
    Remember: if you get an error, show the entire error. Also remember to show the minimal reproducible example for your code, because right now your while loop isn't even closed properly, and there's no public main around it, nor a class around that. And finally, look at your post after you submit it, and then edit it to fix things like indentation being wildly off =) Commented Aug 3, 2023 at 22:31
  • 1
    Guessing as we have partial code, but in place of int age = sc.nextInt(); try int age = sc.nextInt();sc.nextLine(); Commented Aug 3, 2023 at 22:39
  • 1
    With this code yo need to enter the name and the age on separate lines. Is that what you're doing? and is that the intent? If not, change String name = sc.nextLine(); to String name = sc.next();. Commented Aug 3, 2023 at 23:06
  • Thanks for all your answers. So the complet error is : Exception in thread "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) Commented Aug 4, 2023 at 0:15
  • 1
    @OldDogProgrammer No it doesn't. Look again. Commented Aug 4, 2023 at 1:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.