Search code examples
javafloating-pointintegerjava.util.scannerinputmismatchexception

Scanner.next... throws java.util.InputMismatchException for Float but not for Int


Why does Java throw an error when using Scanner.nextFloat() but not Scanner.nextInt() ?

package myshit;

import java.lang.Math;
import java.util.Scanner;

public class speed2 {
    public static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args){
        float number = keyboard.nextFloat();
        System.out.print("Start");

        }
    }

Input:

2.5

Output:

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 myshit.speed2.main(speed2.java:10)

But just by switching nextFloat to nextInt no error occurs:

package myshit;

import java.lang.Math;
import java.util.Scanner;

public class speed2 {
    public static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args){
        int number = keyboard.nextInt();
        System.out.print("Start");

        }
    }

input:

3

Output:

Start

What am I doing wrong?

Appears i needed to input , instead of . Seems to be because of Eclipse


Solution

  • You should type it like 2,5 not 2.5 ( i think this only happens in Netbeans, funny fact that it get parsed to 2.5 )

    run:
    2,5
    Your number is 2.5
    

    Using the notation 2.5 in Netbeans.

    run:
    2.5
    
    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextFloat(Scanner.java:2345)
    at test.Test.main(Test.java:25)