java:从键盘键入字符串的值

本文介绍了两种在Java中从键盘获取字符串的方法:1. 使用java.util.Scanner类,通过构造方法如Scanner(System.in)实现;2. 使用java.io.BufferedReader类结合InputStreamReader进行读取。并提供了相关代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式1,使用扫描器类 Scanner
方式2,使用BufferedReader


使用java.util.Scanner

		Scanner scan = new Scanner(System.in);
		String line = scan.nextLine();

java.util.Scanner 扫描器类 可以对输入的内容做扫描操作
构造方法:
Scanner(File source)//以文件作为源来进行扫描
Scanner(File source, String charsetName) //以文件作为源来进行扫描 可以指定编码集
Scanner(InputStream source) //以流作为源来进行扫描
Scanner(InputStream source, String charsetName) //以流作为源来进行扫描 可以指定编码集
Scanner(String source) //以字符串为源来进行扫描

示例代码:

	public void pattern_1(){
		//实例化一个扫描器类,以流作为源进行扫描
		Scanner scan = new Scanner(System.in);
		System.out.println("输入一个字符串:");
		String line = scan.nextLine();
		System.out.println("输入值是: "+line);
		scan.close();
	}

参考原文
https://blog.youkuaiyun.com/weixin_43251783/article/details/83753756


使用java.io.BufferedReader

		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		String line = reader.readLine();

示例代码:

	public void pattern_2() {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		try {

			System.out.println("输入一个字符串:");
			String line = reader.readLine();
			System.out.println("输入值是: "+line);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(reader!=null){
				try {
					reader.close();
				} catch (IOException e) {
					
				} finally {
					reader = null;
				}
			}
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值