0

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?

Jonik
  • 80,077
  • 70
  • 264
  • 372
Martin
  • 177
  • 1
  • 11

3 Answers3

0

When inputting a number, you aren't supposed to include commas unless you expect to split it. If you want a decimal, use a "." instead. If you want a number greater than 999, don't include a comma

PsyCode
  • 644
  • 5
  • 14
0

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...

Java Devil
  • 10,629
  • 7
  • 33
  • 48
0

Like many people have said, the comma is messing you up.

One option you may consider if your input needs comma is replacing the commas from the input string before try to count the number of digits.

System.out.println("Enter start number:  ");
String input = marty.nextLine();

float sk = Float.parseFloat(input.replace(",", ".")); // use input.replace(",", "") if you want to remove commas

int numb = (int)Math.log10(sk)+1;
System.out.println(numb);
Jonathan
  • 925
  • 6
  • 19