Java Scanner的简单应用

来源:互联网 发布:log4j linux 绝对路径 编辑:程序博客网 时间:2024/06/05 17:20

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: 6Enter another integer: 3The first number you entered was 6The second number you entered was 3Their sum is 9Their 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 ryeHow much does it weigh (in lbs)?  3How many times have you read it?  1Since 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.