Scanner 可以用于检测并捕捉键盘输入的各种字符串。
Example 1:
import java.util.Scanner;
public class Scanner1 {
/**
* Shows basic use of the scanner
*/
public static void main(String[] args) {
Scanner keyboardInput;
keyboardInput = new Scanner(System.in);
int first, second;
System.out.print("Enter an integer: ");
first = keyboardInput.nextInt();
System.out.print("Enter another integer: ");
second = keyboardInput.nextInt();
System.out.println("The first number you entered was " + first);
System.out.println("The second number you entered was " + second);
int sum = first + second;
int product = first * second;
System.out.println("Their sum is " + sum);
System.out.println("Their product is " + product);
keyboardInput.close();
}
}
输入为:6, 3
输出为:Enter an integer: 6
Enter another integer: 3
The first number you entered was 6
The second number you entered was 3
Their sum is 9
Their product is 18
Example 2:
import java.util.Scanner;
public class Scanner2{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("What is your favorite book? ");
String book = input.nextLine();
System.out.print("How much does it weigh (in lbs)? ");
double weight = input.nextDouble();
System.out.print("How many times have you read it? ");
int timesRead = input.nextInt();
System.out.println();
System.out.println("Since you have read " + book + " " + timesRead + " times,");
System.out.println("and " + book + " weighs " + weight + " pounds,");
System.out.println("you have read " + timesRead * weight + " pounds worth of " + book+".");
input.close();
}
}
输入为:
the catcher in the rye
3
1
输出为:
What is your favorite book? the catcher in the rye
How much does it weigh (in lbs)? 3
How many times have you read it? 1
Since you have read the catcher in the rye 1 times,
and the catcher in the rye weighs 3.0 pounds,
you have read 3.0 pounds worth of the catcher in the rye.