Java Scanner的简单应用

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.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值