Java Get float, double and String Input

https://w‮ttual.ww‬uri.com
Java Get float, double and String Input

To get float, double, and string input from the user in Java, you can use the Scanner class.

Here is an example of how to read float, double, and string input from the user:

Scanner sc = new Scanner(System.in);

System.out.print("Enter a float: ");
float f = sc.nextFloat();

System.out.print("Enter a double: ");
double d = sc.nextDouble();

System.out.print("Enter a string: ");
String s = sc.nextLine();

The Scanner class is used to read input from the console (or from any other input stream, such as a file). The nextFloat method reads a float value from the input, the nextDouble method reads a double value from the input, and the nextLine method reads a string value from the input.

Note that the nextLine method reads the entire line of input, including any leading or trailing white space. If you only want to read the next word (i.e. a sequence of characters separated by white space), you can use the next method instead.

You can also use the hasNext method to check if there is more input available before reading a value. For example:

if (sc.hasNextFloat()) {
    float f = sc.nextFloat();
}

This will read a float value from the input if one is available, and do nothing if there is no float value available.

Created Time:2017-11-03 22:21:03  Author:lautturi