The Scanner class in Java allows user input through methods like nextLine(), nextInt(), and nextDouble(). The next() method only reads input up to the first whitespace, while nextLine() reads the entire line. Java provides output methods like print() and println() to display text on the screen, and printf() allows formatted output by specifying the format before displaying values.
2. The Scanner class is used to get user input, and it is found in the java.util
package.
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our example,
we will use the nextLine() method, which is used to read Strings:
10. Here, we have provided the full name. However, the next() method only reads the
first name.
This is because the next() method reads input up to the whitespace character. Once
the whitespace is encountered, it returns the string (excluding the whitespace).
13. Output
Java provides some simple output statements to send output to the standard output device, the display
screen. Examples of
these output statements are the following:
System.out.print(“This is a text.”);
and
System.out.println(“This is a text.”);
• The print() method displays an output, and the insertion point stays in the current line.
• The println() method moves the insertion point to the following line after the output is displayed.
When displaying a string with variables, simply concatenate them using the plus (+) sign. For example:
String name = “Jess Diaz”;
System.out.println(“Hello! My name is ” + name + “.”);
and
int kilo = 2;
System.out.println(kilo + “ kilos of sugar.”);
The output of print and println methods are in the format of strings.
14. Java includes a method named printf() that can be used to create an output in a specific
format. This method is used to add formatting instructions that specify the output
before displaying it on the display screen, such as modifying the number of digits to
include after a decimal point.
For example, consider the following:
double price = 19.5; System.out.println(“Price using println: ” + price);
System.out.printf(“Price using print formatting: %.2f”, price);
This code outputs the following lines: Price using println: 19.5 Price using printf
formatting: 19.50
15. Using the printf method, the double type variable is formatted to have two (2) decimal places. In this
example, the first argument to %.2f is a string called the format specifier, and the second argument is
the value to be output in that format.
A format specifier is a placeholder for a numeric value. The format specifier %.2f tells the JVM to
return the variable with two (2) digits after the decimal point. The f in %.2f means the output is a
floating-point number.