java唤醒键盘的代码_还债——Java获取键盘输入的三种方法

1.System.in.read()  获取一个字符char

public static void main(String[] args) throws IOException {

char ch = (char)System.in.read();

System.out.println(ch);

}

要注意的是:1.要有异常处理 IOException

2.只能获取单个字符 char型

3.注意强制类型转换

2.BufferedReader 和 InputStreamReader  获取 字符串  readLine()

public static void main(String[] args) throws IOException {

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

String str = bufferedReader.readLine();

System.out.println(str);

}

需要注意的依然是:要有异常处理,还有读取字符串,只能用readLine()

3.Scanner类(推荐)

import java.util.Scanner;

public class Main {

public static void main(String[] args){

Scanner in = new Scanner(System.in);

String str = in.nextLine();

System.out.println(str);

int num = in.nextInt();

System.out.println(num);

long num1 = in.nextLong();

System.out.println(num1);

while(in.hasNext()){

System.out.println(in.next());

}

}

}

注意:使用Scanner类的时候,很轻松的接收到输入的东西  next(), nextInt(), nextFloat(), nextLong() 还有nextLine()

但是nextLine(),与next()的区别是:

next()在接收有效数据前不接收tab 空格 或者enter,在接收到有效数据后,则遇到这些键就退出

nextLine()接收空格,tab,应该以enter结束

java中数组初始化的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值