Home » Java programming language

Java Scanner nextFloat() Method with Example

Scanner Class nextFloat() method: Here, we are going to learn about the nextFloat() method of Scanner Class with its syntax and example.
Submitted by Preeti Jain, on February 18, 2020

Scanner Class nextFloat() method

  • nextFloat() method is available in java.util package.
  • nextFloat() method is used to scans the next token of the input scanned into a float value.
  • nextFloat() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • nextFloat() method may throw an exception at the time of returning float value.
    • InputMismatchException: This exception may throw when the next token input mismatch.
    • NoSuchElementException: This exception may throw when no such element exists.
    • IllegalStateException: This exception may throw when this Scanner is not opened.

Syntax:

    public float nextFloat();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is float, it returns float value for the input.

Example:

// Java program to demonstrate the example 
// of float nextFloat() method of Scanner 

import java.util.*;

public class NextFloatOfScanner {
    public static void main(String[] args) {
        String str = "Hi, true IncludeHelp! 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 the scanner
        sc.close();
    }
}

Output

Float Exists: 8.0





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.