Scanner类的使用

Scanner类的使用

(接受键盘输入)

java.util.Scanner是Java5的新特征,主要功能是简化文本扫描。这个类最实用的地方表现在获取控制台输入,其他的功能都很鸡肋,尽管Java API文档中列举了大量的API方法,但是都不怎么地。

 【代码示例】

 1 public static void main(String[] args) {
 2         test01();
 3         test02();
 4     }
 5 
 6     public static void test02() {
 7         Scanner s=new Scanner(System.in);
 8         System.out.println("请输入一个加数:");
 9         int a=s.nextInt();
10         System.out.println("请输入被加数:");
11         int b= s.nextInt();
12         int sum=a+b;
13         System.out.println("计算结果,和为:"+sum);
14     }
15 
16     public static void test01() {
17         System.out.println("请输入:");
18         Scanner s=new Scanner(System.in); //System.in:键盘输入
19         String str=s.next(); //程序运行到next会阻塞,等待键盘的输入!next返回的是一个字符串
20         System.out.println("刚刚键盘输入了:"+str);
21     }
View Code

一、扫描控制台输入

这个例子是常常会用到,但是如果没有Scanner,你写写就知道多难受了。
当通过new Scanner(System.in)创建一个Scanner,控制台会一直等待输入,直到敲回车键结束,把所输入的内容传给Scanner,作为扫描对象。如果要获取输入的内容,则只需要调用Scanner的nextLine()方法即可。

/** 
* 扫描控制台输入 
* 
* @author leizhimin 2009-7-24 11:24:47 
*/ 
public class TestScanner { 
        public static void main(String[] args) { 
                Scanner s = new Scanner(System.in); 
                System.out.println("请输入字符串:"); 
                while (true) { 
                        String line = s.nextLine(); 
                        if (line.equals("exit")) break; 
                        System.out.println(">>>" + line); 
                } 
        } 
}

控制台输出:

请输入字符串: 
234 
>>>234 
wer 
>>>wer 
bye 
>>>bye 
exit 

Process finished with exit code 0

二、如果说Scanner使用简便,不如说Scanner的构造器支持多种方式,构建Scanner的对象很方便。

可以从字符串(Readable)、输入流、文件等等来直接构建Scanner对象,有了Scanner了,就可以逐段(根据正则分隔式)来扫描整个文本,并对扫描后的结果做想要的处理。

三、Scanner默认使用空格作为分割符来分隔文本,但允许你指定新的分隔符

使用默认的空格分隔符:

  public static void main(String[] args) throws FileNotFoundException { 
                Scanner s = new Scanner("123 asdf sd 45 789 sdf asdfl,sdf.sdfl,asdf    ......asdfkl    las"); 
//                s.useDelimiter(" |,|\."); 
                while (s.hasNext()) { 
                        System.out.println(s.next()); 
                } 
        }

控制台输出:

123 
asdf 
sd 
45 
789 
sdf 
asdfl,sdf.sdfl,asdf 
......asdfkl 
las 

Process finished with exit code 0

将注释行去掉,使用空格或逗号或点号作为分隔符,输出结果如下:

123 
asdf 
sd 
45 
789 
sdf 
asdfl 
sdf 
sdfl 
asdf 







asdfkl 

las 

Process finished with exit code 0
原文地址:https://www.cnblogs.com/Qian123/p/5164791.html