方式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 }
功能较全,推荐使用。