Since you're using nextFloat() you must be sure that you enter a floating number, otherwise clear the scanner with next()

public static void main(String[] args) throws Exception {
    while (true) {
        System.out.print("Enter a float: ");
        try {
            float myFloat = input.nextFloat();
            if (myFloat % 1 == 0) {
                throw new Exception("Wrong type");
            }
            System.out.println(myFloat);
        } catch (InputMismatchException ime) {
            System.out.println(ime.toString());
            input.next(); // Flush the buffer from all data
        }
    }
}

Results:

UPDATE

You still have to handle the InputMismatchException, just throw your own exception in the catch block.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    // while (true) just for testing
    while (true) {
        try {
            System.out.print("Enter a float: ");
            System.out.println(CheckFloat(input));
        } catch (MyException me) {
            System.out.println(me.toString());
        }
    }
}

private static float CheckFloat(Scanner sc) throws MyException {
    try {
        float input = sc.nextFloat();
        if (input % 1 == 0) {
            throw new MyException("Wrong type");
        } else {
            return input;
        }
    } catch (InputMismatchException ime) {
        sc.next(); // Flush the scanner

        // Rethrow your own exception
        throw new MyException("Wrong type");
    }
}

private static class MyException extends Exception {
    // You exception details
    public MyException(String message) {
        super(message);
    }
}

Results:

Answer from Shar1er80 on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › home › java/util › java scanner nextfloat method
Java Scanner nextFloat Method
September 1, 2008 - The Java Scanner nextFloat() method scans the next token of the input as a float. This method will throw InputMismatchException if the next token cannot be translated into a valid float value as described below.
🌐
W3Schools
w3schools.com › java › ref_scanner_nextfloat.asp
Java Scanner nextFloat() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... // Create a scanner object Scanner myObj = new Scanner("The probability is 45.6 percent"); // Print the value of every floating point number in the scanner while (myObj.hasNext()) { if (myObj.hasNextFloat()) { System.out.println(myObj.nextFloat()); } else { myObj.next(); } }
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Scanner.html
Scanner (Java Platform SE 8 )
October 20, 2025 - If the translation is successful, the scanner advances past the input that matched. If the next token matches the Float regular expression defined above then the token is converted into a float value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Float.parseFloat.
🌐
GeeksforGeeks
geeksforgeeks.org › java › scanner-nextfloat-method-in-java-with-examples
Scanner nextFloat() method in Java with Examples - GeeksforGeeks
July 11, 2025 - Not found Float() value :Gfg Found Float value :9.0 Not found Float() value :+ Found Float value :6.0 Not found Float() value := Found Float value :12.0 Program 2: To demonstrate InputMismatchException ... // Java program to illustrate the // nextFloat() method of Scanner class in Java // InputMismatchException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg 9 + 6 = 12.0"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Float // print found and the Float // since the value 60 is out of range // it throws an exception System.out.println("Next Float value :" + scanner.nextFloat()); } scanner.close(); } catch (Exception e) { System.out.println("Exception thrown: " + e); } } }
🌐
Code-reference
code-reference.com › java › util › scanner › nextfloat
java util scanner nextfloat Programming | Library | Reference - Code-Reference.com
package scanner; import java.util.Scanner; public class Scanner { public static void main(String[] args) { /* Create Scanner Object for the input from the keyboard */ Scanner scan = new Scanner(System.in); float currency; System.out.print("Please enter a number: "); currency = scan.nextFloat(); // read currency System.out.println("Number is " + currency); scan.close(); // close the object } } Please enter a number: 42,42 Number is 42.42 ·
🌐
Tabnine
tabnine.com › home page › code › java › java.util.scanner
java.util.Scanner.nextFloat java code examples | Tabnine
Scanner scanner = new Scanner(input).useDelimiter(","); long time = scanner.nextLong(); float yaw = scanner.nextFloat(); float pitch = scanner.nextFloat(); float roll = scanner.nextFloat(); ... import java.io.*; import java.util.Scanner; public ...
🌐
Javatpoint
javatpoint.com › post › java-scanner-nextfloat-method
Java Scanner nextFloat() Method - Javatpoint
The nextFloat() method of Java Scanner class is used to scan the next token of the input as a Float. If the translation is successful, the scanner past the input that matched · Following is the declaration of nextFloat() method:
Find elsewhere
🌐
IncludeHelp
includehelp.com › java › scanner-nextfloat-method-with-example.aspx
Java Scanner nextFloat() Method with Example
8 + 2.0f = 10.0f"; // Instantiate Scanner with the // given str Scanner sc = new Scanner(str); // Loop for scanning the float // token input while (sc.hasNext()) { // if float then display it if (sc.hasNextFloat()) { System.out.println("Float Exists: " + sc.nextFloat()); } sc.next(); } // close ...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › Scanner.html
Scanner (Java Platform SE 7 )
If the translation is successful, the scanner advances past the input that matched. If the next token matches the Float regular expression defined above then the token is converted into a float value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Float.parseFloat.
🌐
AlphaCodingSkills
alphacodingskills.com › java › notes › java-scanner-nextfloat.php
Java Scanner nextFloat() Method - AlphaCodingSkills
import java.util.*; public class MyClass { public static void main(String[] args) { //String to scan String MyString = "Hello World 10 + 20 = 30.0"; //creating a Scanner Scanner MyScan = new Scanner(MyString); while(MyScan.hasNext()) { //if the next is a float if(MyScan.hasNextFloat()) System.out.println("Float value is: "+ MyScan.nextFloat()); //if the next is not a float else System.out.println("No Float Value found: "+ MyScan.next()); } //close the scanner MyScan.close(); } }
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.util.scanner.nextfloat
Scanner.NextFloat Method (Java.Util) | Microsoft Learn
Scans the next token of the input as a float. This method will throw InputMismatchException if the next token cannot be translated into a valid float value as described below. If the translation is successful, the scanner advances past the input ...
🌐
Javatpoint
javatpoint.com › post › java-scanner-hasnextfloat-method
Java Scanner hasNextFloat() Method - Javatpoint
The hasNextFloat() is a method of Java Scanner class which is used to check if the next token in this scanner's input can be interpreted as a float value using the nextFloat() method. It returns true if the scanner's input can be interpreted as a float value, otherwise returns false · Following ...
🌐
TutorialsPoint
tutorialspoint.com › home › java/util › java scanner hasnextfloat() method
Java Scanner hasNextFloat() Method
March 25, 2025 - Learn how to use the hasNextFloat() method in Java's Scanner class to check if the next input is a float value. Detailed examples and explanations included.
🌐
GeeksforGeeks
geeksforgeeks.org › java › scanner-hasnextfloat-method-in-java-with-examples
Scanner hasNextFloat() method in Java with Examples - GeeksforGeeks
July 11, 2025 - // Java program to illustrate the // hasNextFloat() method of Scanner class in Java // Exception case import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "gfg 2 geeks!"; // new scanner with the // specified String Object Scanner scanner = new Scanner(s); // use US locale to interpret Floats in a string scanner.useLocale(Locale.US); scanner.close(); // iterate till end while (scanner.hasNext()) { // check if the scanner's // next token is a Float with the default radix System.out.print("" + scanner.hasNextFloat()); // print what is scanned System.out.print(" -> " + scanner.next() + "\n"); } // close the scanner scanner.close(); } catch (IllegalStateException e) { System.out.println("Exception: " + e); } } }
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › util › Scanner.html
Scanner (Java SE 9 & JDK 9 )
If the translation is successful, the scanner advances past the input that matched. If the next token matches the Float regular expression defined above then the token is converted into a float value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Float.parseFloat.
Top answer
1 of 3
1

Here is what's going on.

When the you use the hasNext(Pattern) method, the scanner looks at its complete next token and decides whether that complete token matches the pattern or not.

When the delimiter is empty, it means that the complete next token is a single character. You can see that if you try to use String.split() with an empty pattern.

So, when you enter 123.4.5, what hasNext() actually sees is just the 1. Luckily, that matches your pattern, so you get into the body of the if.

At this point, you are using findInLine(pattern). This method disregards delimiters and tokens, and instead simply looks for a matching pattern. So it sees the whole 123.4 and gives that to you.

Now that you are left with .5, the next complete token is just the .! This doesn't match the pattern (your pattern says that if there is a . it has to be followed by at least one digit. A single dot doesn't match). Therefore, the hasNext(integerPattern) fails, and you get to the else part.

Here is a possible solution: have different patterns for the hasNext and for the findInLine:

    Pattern findPattern = Pattern.compile("\\d*(\\.\\d+)?");
    Pattern tokenPattern = Pattern.compile("\\d|\\.(?=\\d)");

The tokenPattern has a positive look-ahead which means that it will accept a single-character token that is either:

  • A digit
  • A dot - provided that there are digits after it, though they are not in the match.

If you have a single char that matches these criteria you know you'll be able to match the full pattern. So your program changes to:

while (interpreter.hasNext()) {

    // Do we have the beginning of a number?
    if (interpreter.hasNext(tokenPattern)) {
        // Extract the full number
        String strVal = interpreter.findInLine(findPattern);
        float value = Float.parseFloat(strVal);
        tokenList.add(new Token(11, value));

    }
    else{
        // Handle single char token
    }
 }
2 of 3
1

This will scan in the next float.

Scanner interpreter = new Scanner(input);
while(interpreter.hasNextFloat()){
    tokenList.add(newToken(11, scanner.nextFloat()));
}
🌐
YouTube
youtube.com › watch
How to Take Float Input from User in Java - YouTube
Learn How to get float value input from keyboard in java language. You need to use scanner class methods to accept float inputs. Video is available in HD.
Published   February 27, 2014