How to Enter a Float Literal in Java
Java programs can take a wide variety of keyboard user inputs. You can enter strings and any primitive numerical type: integer, long, float or double (double-precision float). In principle, all console input is just a stream of uninterpreted bytes -- so you need to call the appropriate Java library functions to parse a particular input as a float. When the application executes, the user will provide that particular input by following Java's syntax rules for float literals (constant values).
Instructions
-
-
1
Include the following line at the beginning of your Java code:
import java.io.*;
-
2
Write code that creates an instance of the pre-defined BufferedReader Java class to read input from the console, as in the following sample code:
BufferedReader myInputStream = new BufferedReader(new InputStreamReader(System.in));
"System.in" is the input stream defined for every Java application, also called "standard input."
-
-
3
Include code that reads a float number from the BufferedReader object:
float myFloat;
myFloat = Float.parseFloat(myInputStream.readLine());
-
4
Compile your whole Java application, including the code added in Steps 1 through 3, by clicking "Start," then typing "cmd" into the search box and pressing "Enter." A new Command line will open. Type the following command into it:
javac myMainClass.java
Replace "myMainClass.java" by the name of the file containing the source Java code. Press "Enter."
-
5
Execute your Java application by typing the following command into the Command window:
java myMainClass.class
Press "Enter."
-
6
Enter the float literal when your code prompts you for it by typing it as in the following example:
2.71828
Press "Enter." The Java program will parse the float literal and store its value into the variable "myFloat."
-
1