Java 读取控制台输入

 

方式1:InputStreamReader+BufferedReader

 1 package my_package;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 
 7 public class Test {
 8     public static void main(String[] args) {
 9         InputStreamReader isr=new InputStreamReader(System.in);
10         BufferedReader br=new BufferedReader(isr);
11         try {
12             //不加缓冲区,只能读取char的ASCII码值。回车表示输入结束
13             String str=br.readLine();
14             System.out.println(str);
15         } catch (IOException e) {
16             e.printStackTrace();
17         }
18 
19     }
20 
21 }

此方式的读取方式十分有限,不能满足很多功能,不推荐使用。

 

 

 

方式2:使用Scanner

 1 package test;
 2 
 3 import java.util.Scanner;
 4 
 5 public class Test {
 6     public static void main(String[] args) {
 7         //System.in表示标准输入,即键盘输入
 8         Scanner sc=new Scanner(System.in);
 9 
10         //定义分隔符(单个输入结束的标志),默认使用回车
11         //sc.useDelimiter("\n");    //参数可以使String或者Pattern
12 
13         String str;
14 
15         //如果还有下一个输入项。hasNextXxx()表示判断是否还有某个基础数据类型的输入
16         while(sc.hasNext()){
17             //获取用户输入.nextXxx()表示某个基础数据类型的输入
18             str=sc.next();
19             System.out.println(str);
20         }
21 
22     }
23 }

 

 1 package test;
 2 
 3 import java.util.Scanner;
 4 
 5 public class Test2 {
 6     public static void main(String[] args) {
 7         Scanner sc=new Scanner(System.in);
 8         int i;
 9         //输入为int型的值时,才执行,否则break。比如下一个输入一个字符串,这个while就break了
10         while(sc.hasNextInt()){
11            i=sc.nextInt();
12             System.out.println(i);
13         }
14 
15     }
16 
17 }

 

 1 package test;
 2 
 3 import java.util.Scanner;
 4 
 5 public class Test3 {
 6     public static void main(String[] args) {
 7         Scanner sc=new Scanner(System.in);
 8         String str;
 9         //是否还有下一行输入
10         while (sc.hasNextLine()){
11             //读取一行,作为字符串返回
12             str=sc.nextLine();
13             System.out.println(str);
14         }
15 
16     }
17 
18 }

 

功能较全,推荐使用。

 

转载于:https://www.cnblogs.com/chy18883701161/p/10852181.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值