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++;
Vincent
  • 1
  • 1
  • 2
    Remember: if you get an error, [show the entire error](/help/how-to-ask). Also remember to show the [mcve] 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 =) – Mike 'Pomax' Kamermans Aug 03 '23 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();` – g00se Aug 03 '23 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();`. – user207421 Aug 03 '23 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) – Vincent Aug 04 '23 at 00:15
  • It works with sc.next() but I cant add big names ( name + surname). I will do with next(). Thank you all. – Vincent Aug 04 '23 at 00:24
  • You can't add space-separated names. If you want first name and surname you will need two variables and two `next()` calls. – user207421 Aug 04 '23 at 01:13
  • 1
    @OldDogProgrammer No it doesn't. Look again. – user207421 Aug 04 '23 at 01:13
  • I missed the first one so: `int numPeople = sc.nextInt();sc.nextLine();` but it's really not helping that you still haven't at least closed the loop as a 'minrep' – g00se Aug 04 '23 at 08:06

0 Answers0