Search code examples
javaeclipseinputmismatchexception

Scanner.next() - Exception in thread "main" java.util.InputMismatchException


Hi guys I am a total newbie. Please help me.

The program is:

import java.util.Scanner.*;
import java.lang.*;
public class HexToDecimalFromWeb{
public static void main (String [] args) {
    Scanner input = new Scanner(System.in);
    printHeader();
    while (true) {
        String hex = input.next("Enter a hexadecimal number: ");
        int dec = Integer.parseInt(hex, 16);
        if (dec == SENTINEL) {
            break;
        }
        System.out.println(hex + " hex = " +  
         Integer.toString(dec)+ "decimal");
    }
}
private static void printHeader() {
    System.out.println("This program converts hexadecimal to decimal.");
   System.out. println("Enter 0 to stop.");
}
private static final int SENTINEL = 0;
}

The error I get is this:

java.lang.NoClassDefFoundError: HexToDecimalFromWeb
Caused by: java.lang.ClassNotFoundException: HexToDecimalFromWeb
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)

What is the reason for that?

I think it may be an issue with Eclipse as some other programs won't run either.

11.2019 UPDATE :

I tried to execute this code again in a different IDE, this is not a problem with Eclipse. The error I am getting is this:

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.next(Scanner.java:1525)
at HexToDecimalFromWeb.main(HexToDecimalFromWeb.java:12)

Solution

  • The problem was the below line:

    String hex = input.next("Enter a hexadecimal number: ");
    

    Java Scanner method next() does not accept a random String as its argument. It can either have no argument or an argument such as String pattern or Pattern pattern.

    These are the declarations of next() method:

    public String next()  
    public String next(String pattern)  
    public String next(Pattern pattern)