0

I am having some trouble getting my Scanner to behave correctly. When i am using scanner.next(); with a two word input, the compiler is complaining. Yet when I try to use scanner.nextLine(); the next questions text is appearing at the cursor, instead of letting me enter an input. I'm sorry for the terrible explanation, I am new to Java and don't have many describing words as of yet.

Thank you in advance!

My code:

private static List<Person> readInPeople() {

        List<Person> people = new LinkedList<>();
        Scanner sc = new Scanner(System.in);
        
        System.out.print("How many people are there? ");
        int numberOfPeople = sc.nextInt();

        for (int i = 0; i < numberOfPeople; i++) {
            System.out.println("What type of person is it?");
            System.out.println("1. Student");
            System.out.println("2. Academic");
            System.out.println("3. Code Monkey");
            System.out.print("Enter a choice: ");
            int personType = sc.nextInt();
            
            System.out.print("What is the person's name? ");
            String name = sc.next();
        

            switch (personType) {
                case 1:
                    System.out.print("What degree are they studying?");
                    String degree = sc.next();

                    System.out.print("What year are they in?");
                    int year = sc.nextInt();

                    people.add(new Student(name,degree,year));
                    break;

output when using scanner.next();:

How many people are there? 1
What type of person is it?
1. Student
2. Academic
3. Code Monkey
Enter a choice: 1
What is the person's name? Alice
What degree are they studying?Computer Science
What year are they in?Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:943)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextInt(Scanner.java:2263)
at java.base/java.util.Scanner.nextInt(Scanner.java:2217)
at Runner.readInPeople(Runner.java:33)
at Runner.main(Runner.java:58)

And output when using sc.nextLine();

How many people are there? 1
What type of person is it?
1. Student
2. Academic
3. Code Monkey
Enter a choice: 1
What is the person's name? Alice
What degree are they studying?What year are they in?Computer Science
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:943)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextInt(Scanner.java:2263)
at java.base/java.util.Scanner.nextInt(Scanner.java:2217)
at Runner.readInPeople(Runner.java:33)
at Runner.main(Runner.java:58)
  • If you want to scan multiple words as a single line of text, you can use nextLine(); but see the linked duplicate for how to deal with problems mixing nextLine with other next* methods. – khelwood May 22 '22 at 10:07

0 Answers0