Hello all, I've been fooling around with some code trying to teach myself somewhat about Linked Lists. I wrote this quick program that creates a random number in each node of a list and asks the user to guess the number. I have a quit choice that, when executed alone (no prior menu choice used) works perfectly. If the user, though, were to choose option 1 or 2 before attempting to quit, the program would throw an InpurMismatchException. I'm just curious as to why this is happening.

I'm not sure what's triggering the error. My guess would be something with my

keyboard.nextInt()

statements, but that's just a wild guess.

Here's the code:

package linkedtest;

import java.util.LinkedList;
import java.util.Random;
import java.util.Scanner;

public class LinkedTest {

    public static int getMenuChoice() {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("\nEnter a menu choice: "
                + "\n1) Generate randomized list"
                + "\n2) Guess number"
                + "\n3) Quit");

        return keyboard.nextInt();
    }
    public static void main(String[] args) {
        LinkedList<Integer> test = new LinkedList<Integer>();
        
        Random generator = new Random();
        Scanner keyboard = new Scanner(System.in);
        
        int randQuant = 0;
        int guess = 0;
        String askQuit;
        
        int menuChoice;
        menuChoice = getMenuChoice();
        boolean areWeDone = false;
        
        while (!areWeDone) {
            if (menuChoice == 3) {
                System.out.println("\nAre you sure you want to quit? (Y/N)");
                askQuit = keyboard.nextLine().toUpperCase();

                if (askQuit.equals("Y")) {
                    areWeDone = true;
                    break;
                }
            }

            switch (menuChoice) {
                case 1:
                    
                    System.out.println("Enter range for random number "
                            + "generation: ");
                    randQuant = keyboard.nextInt();

                    for( int i = 0; i < 30; i++){
                        int rand = generator.nextInt(randQuant);
                        test.add(rand);
                    }
                    
                    System.out.println("List as been generated.");
                    
                    break;
                    
                case 2:
        
                    System.out.println("Guess a number from 0 to " + randQuant);
                    guess = keyboard.nextInt();
                    
                    if(test.contains(guess)){
                        System.out.println(guess + " is in the list.");
                        test.remove(guess);
                    }
                    
                    else {
                        System.out.println("Number not in the list, try again.");
                    }
                    
                    break;
                    
            }
            
            menuChoice = getMenuChoice();
    }
  }
}

and the error:

Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:909)
	at java.util.Scanner.next(Scanner.java:1530)
	at java.util.Scanner.nextInt(Scanner.java:2160)
	at java.util.Scanner.nextInt(Scanner.java:2119)
	at linkedtest.LinkedTest.getMenuChoice(LinkedTest.java:18)
	at linkedtest.LinkedTest.main(LinkedTest.java:79)
Java Result: 1

Thanks!

Dani AI

Generated

Short diagnosis: the exception means a Scanner call that expected an integer actually found non-numeric input. is right that entering "Y" will trigger that when nextInt() runs, but the practical root causes here are (a) creating multiple Scanner objects on System.in and (b) mixing token-based reads (nextInt()) with line-based reads (nextLine()), which leaves input you don't expect in the stream.

Why that combination bites you: a nextInt() leaves the rest of the line (the newline) behind; nextLine() will consume that leftover and sometimes return an empty string instead of the user confirmation, leaving the actual "Y" for the next nextInt() call. Multiple Scanner instances make this worse because each scanner buffers input independently and can read ahead. That ordering explains why quitting works if you choose 3 first but fails after doing option 1 or 2.

Practical fixes you can apply right away:

  • Use a single Scanner for the whole program (pass it into helper methods or make it a single field).
  • Prefer line-oriented reads: read in.nextLine() and parse with Integer.parseInt() inside a try/catch loop to validate input.
  • If you must use nextInt(), immediately call nextLine() to clear the rest of that line before any nextLine() string read.
  • For Y/N, use in.next() and equalsIgnoreCase("Y") (then in.nextLine() if you need to clear the remainder).
  • Validate with hasNextInt() or handle NumberFormatException to avoid crashes.

Example pattern to reuse one Scanner and validate a numeric menu choice:

private static int getMenuChoice(Scanner in) {
  System.out.println("Enter a menu choice: 1) ... 2) ... 3) Quit");
  while (true) {
    String line = in.nextLine().trim();
    try {
      int choice = Integer.parseInt(line);
      if (choice >= 1 && choice <= 3) return choice;
    } catch (NumberFormatException e) { }
    System.out.println("Please enter 1, 2 or 3:");
  }
}

This keeps input handling predictable and prevents the InputMismatchException you saw.

Hello all, I've been fooling around with some code trying to teach myself somewhat about Linked Lists. I wrote this quick program that creates a random number in each node of a list and asks the user to guess the number. I have a quit choice that, when executed alone (no prior menu choice used) works perfectly. If the user, though, were to choose option 1 or 2 before attempting to quit, the program would throw an InpurMismatchException. I'm just curious as to why this is happening.

I'm not sure what's triggering the error. My guess would be something with my

keyboard.nextInt()

statements, but that's just a wild guess.

Here's the code:

package linkedtest;

import java.util.LinkedList;
import java.util.Random;
import java.util.Scanner;

public class LinkedTest {

    public static int getMenuChoice() {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("\nEnter a menu choice: "
                + "\n1) Generate randomized list"
                + "\n2) Guess number"
                + "\n3) Quit");

        return keyboard.nextInt();
    }
    public static void main(String[] args) {
        LinkedList<Integer> test = new LinkedList<Integer>();
        
        Random generator = new Random();
        Scanner keyboard = new Scanner(System.in);
        
        int randQuant = 0;
        int guess = 0;
        String askQuit;
        
        int menuChoice;
        menuChoice = getMenuChoice();
        boolean areWeDone = false;
        
        while (!areWeDone) {
            if (menuChoice == 3) {
                System.out.println("\nAre you sure you want to quit? (Y/N)");
                askQuit = keyboard.nextLine().toUpperCase();

                if (askQuit.equals("Y")) {
                    areWeDone = true;
                    break;
                }
            }

            switch (menuChoice) {
                case 1:
                    
                    System.out.println("Enter range for random number "
                            + "generation: ");
                    randQuant = keyboard.nextInt();

                    for( int i = 0; i < 30; i++){
                        int rand = generator.nextInt(randQuant);
                        test.add(rand);
                    }
                    
                    System.out.println("List as been generated.");
                    
                    break;
                    
                case 2:
        
                    System.out.println("Guess a number from 0 to " + randQuant);
                    guess = keyboard.nextInt();
                    
                    if(test.contains(guess)){
                        System.out.println(guess + " is in the list.");
                        test.remove(guess);
                    }
                    
                    else {
                        System.out.println("Number not in the list, try again.");
                    }
                    
                    break;
                    
            }
            
            menuChoice = getMenuChoice();
    }
  }
}

and the error:

Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:909)
	at java.util.Scanner.next(Scanner.java:1530)
	at java.util.Scanner.nextInt(Scanner.java:2160)
	at java.util.Scanner.nextInt(Scanner.java:2119)
	at linkedtest.LinkedTest.getMenuChoice(LinkedTest.java:18)
	at linkedtest.LinkedTest.main(LinkedTest.java:79)
Java Result: 1

Thanks!

The problem is here:

public static int getMenuChoice() {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("\nEnter a menu choice: "
                + "\n1) Generate randomized list"
                + "\n2) Guess number"
                + "\n3) Quit");

        return keyboard.nextInt();
    }

when the user enters 'Y' to quit it tries to read an integer but of course it recieves a character/string thats whats throwing the exception....use nextLine() method and then check if its 'y' or 'n' then work appropriately if its neither convert to a integer... any exception thrown by the conversion is an actual input mismatch
[edit] This would mean that you'd have to take away all other checks for y or n and make it all coincide with getMenuChoice. Also use equalsIgnoreCase() method

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.