Search code examples
javajava.util.scannerinputmismatchexception

Error in Java while trying to read input


This program should count amount of digits in a number.
Here is my code:

import java.util.Scanner;

public class Converter {
    public static void main(String[] args) {
        Scanner marty = new Scanner(System.in);
        float sk; 

        System.out.println("Enter start number:  ");
        sk = marty.nextFloat();

        int numb = (int)Math.log10(sk)+1;
        System.out.println(numb);

        marty.close();
    }
}

I am getting this kind of error, while tryin to input number with 4 or more digits before comma, like 11111,456:

Exception in thread "main" java.util.InputMismatchException  
at java.util.Scanner.throwFor(Unknown Source)  
at java.util.Scanner.next(Unknown Source)  
at java.util.Scanner.nextFloat(Unknown Source)   
at Converter.main(Converter.java:11)

Any ideas about what the problem may be?


Solution

  • Taking the log (base10) of a number and adding 1 is not going to give you the correct answer for the number of digits of the input number anyway.

    Your given example of 11111.465 has 8 digits. The log10 of this number is 4.045... adding 1 gives you the answer of 5.

    Another example: 99, Log10(99) = 1.99, cast as int = 2, add 1 = 3... clearly is only 2 digits.

    You could just read the input as a String then do something like the following instead

    int count = 0;
    String s = /* (Input Number) */
    for(char c : s.toCharArray())
    {
        if(Character.isDigit(c))
            count++;
    }
    

    You would have to also have to check it is actually a number though by checking its pattern...