Java Reference
In-Depth Information
}
else {
console.printf("Invalid password");
}
}
}
If you want to read numbers from the standard input, you have to read it as a string and parse it to a number.
The
Scanner
class in
java.util
package reads and parses a text, based on a pattern, into primitive types and strings.
The text source can be an
InputStream
, a file, a
String
object, or a
Readable
object. You can use a
Scanner
object to
read primitive type values from the standard input
System.in
. It has many methods named liked
hasNextXxx()
and
nextXxx()
, where
Xxx
is a data type, such as
int
,
double
, etc. The
hasNextXxx()
method checks if the next token from
the source can be interpreted as a value of the
Xxx
type. The
nextXxx()
method returns a value of a particular data type.
Listing 7-42 illustrates how to use the
Scanner
class by building a trivial calculator to perform addition,
subtraction, multiplication, and division.
Listing 7-42.
Using the Scanner Class to Read Inputs from the Standard Input
// Calculator.java
package com.jdojo.io;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// Read three tokens from the console: operand-1 operation operand-2
String msg = "You can evaluate an arithmetic expressing.\n" +
"Expression must be in the form: a op b\n" +
"a and b are two numbers and op is +, -, * or /." +
"\nPlease enter an expression and press Enter: ";
System.out.print(msg);
// Build a scanner for the standard input
Scanner scanner = new Scanner(System.in);
double n1 = Double.NaN;
double n2 = Double.NaN;
String operation = null;
try {
n1 = scanner.nextDouble();
operation = scanner.next();
n2 = scanner.nextDouble();
double result = calculate(n1, n2, operation);
System.out.printf("%s %s %s = %.2f%n", n1,
operation, n2, result);
}
catch (Exception e) {
System.out.println("An invalid expression.");
}
}