Now, we will write a program to take user input through the console and convert it to the corresponding float value. Update the main
method with the following code:
Scanner sc = new Scanner(System.in);
System.out.print("Enter a float value: ");
String input = sc.nextLine();
Float f = Float.valueOf(input);
System.out.println("Value of input as float: " + f.floatValue());
In this code, we first create a Scanner
object to read input from the console. We then prompt the user to enter a float
value and store the input in a String
variable named input
. We then convert this String
value to a Float
object using the valueOf()
method. Finally, we use the floatValue()
method to get the corresponding float
primitive value and print it to the console.