Java获取用户的输入

来源:互联网 发布:淘宝网免费注册账号 编辑:程序博客网 时间:2024/05/01 17:38

Java获取用户的输入可以使用Scanner和流的方式,在这里我介绍两种方法

1.使用Scanner

  1. import java.util.Scanner;  
  2. public class Test {  
  3.     public static void main(String[] args) {  
  4.           
  5.         Scanner sc=new Scanner(System.in);  
  6.         while(sc.hasNext())  
  7.         {  
  8.             System.out.println("输出:"+sc.next());  
  9.         }  
  10.   
  11.     }  
  12. }  
使用Scanner的方式获取用户的输入的话,Scanner默认使用空格,Tab,回车作为输入项的分隔符。

可以使用sc.useDelimiter()方法来改变这种默认。

sc可以读取特定的数据,比如int,long看下图


从图中可以看到nextBoolean,nextFloat等等。

Scanner提供一个简单的方法一行一行的读取

  1. import java.util.Scanner;  
  2. public class Test {  
  3.     public static void main(String[] args) {  
  4.           
  5.         Scanner sc=new Scanner(System.in);  
  6.           
  7.         while(sc.hasNextLine())  
  8.         {  
  9.             System.out.println("输出:"+sc.nextLine());  
  10.         }  
  11.   
  12.     }  
  13. }  

Scanner不仅可以读取用户键盘的输入,也可以读取文件

  1. import java.io.File;  
  2. import java.util.Scanner;  
  3.   
  4. public class Test {  
  5.     public static void main(String[] args) throws Exception  
  6.     {  
  7.           
  8.         Scanner sc=new Scanner(new File("C:\\Users\\zhycheng\\Desktop\\Dota超神\\描述.txt"));  
  9.           
  10.         while(sc.hasNextLine())  
  11.         {  
  12.             System.out.println("输出:"+sc.nextLine());  
  13.         }  
  14.   
  15.     }  
  16. }  

2.使用BufferedReader

需要指出的是Scanner是Java5提供的工具类,在Java5之前使用BufferedReader来读取

  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3.   
  4. public class Test {  
  5.     public static void main(String[] args) throws Exception  
  6.     {  
  7.           
  8.         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  9.         String str=null;  
  10.         while((str=br.readLine())!=null)  
  11.         {  
  12.             System.out.println(str);  
  13.         }  
  14.   
  15.     }  
  16. }  
0 0