码迷,mamicode.com
首页 > 编程语言 > 详细

Java获取用户的输入

时间:2015-07-10 15:25:38      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:json   java   

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. }  

版权声明:本文为博主http://www.zuiniusn.com原创文章,未经博主允许不得转载。

Java获取用户的输入

标签:json   java   

原文地址:http://blog.csdn.net/u013948191/article/details/46829011

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!