谈谈java从键盘输入的三种方式

一、从控制台输入一个字符、并且把它打印出来。

package com.cn.in;
import java.io.IOException;
public class ex1 {
	public static void main(String[] args) throws IOException {
	  System.out.print("Enter a Char:");
	  //输入一个字符 
     char i = (char) System.in.read(); 
      System.out.println("your char is :"+i); 
	}
}

二、从控制台输入一个字符串、并且将其打印出来。

package com.cn.in;
import java.io.*;
public class ex2 {
	public static void main(String[] args) throws IOException {
		//InputStreamReader 转换流
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));		
		String str=null;
		System.out.println("请输入:");
		str=br.readLine();
		System.out.println("你输入的内容为:"+str);	
	}
}

注:
str=br.readLine()的作用是将键盘上读取的数据作为字符串处理,如果想读取单个字符,需要将str声明为char类型,然后再使用read()语句进行读取,即:str=(char)br.read();

package com.cn.in;
import java.io.*;
public class ex1 {
	public static void main(String[] args) throws IOException {
		//InputStreamReader 转换流
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));		
		char c;
		System.out.println("请输入:");
		c=(char)br.read();
		System.out.println("你输入的内容为:"+c);	
	}
}

三、通过Scanner类。

package com.cn.in;
import java.util.Scanner;
public class ex3 {
	public static void main(String[] args) {
		Scanner reader=new Scanner(System.in);
		int num;//可以是其他类型	
		num=reader.nextInt();//调用reader的相应方法
		System.out.println("输入的内容是:"+num);
		}
	}

注:

取单个字符也可以这样处理:
Scanner sc=new Scanner(System.in);
char c = sc.next().charAt(0);

next()、nextLine()方法的区别:
next() :从控制台输入的第一个有效字符开始读取,输入字符(串)前面和后面的Tab、空格、回车都不读取
nextLine() :读取输入的全部字符,以回车作为结尾(不读取回车),字符(串)中的Tab、空格都会被读取。
下面来看一个例子:

package com.cn.in;
import java.util.Scanner;
public class Test {
	public static void main(String[] args) {
String str1=null;
String str2=null;
Scanner sc=new Scanner(System.in); 
System.out.print("请输入第一个字符串:");  
str1=sc.nextLine(); 
System.out.println("输入的字符串是:"+str1);
System.out.print("请输入第二个字符串:"); 
str2=sc.next(); 
System.out.println("输入的字符串是:"+str2);
	}
}

在这里插入图片描述

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小Java开发者

“是一种鼓励,你懂的”

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值