java中的Scanner的整理

1.包:

import java.util.Scanner

2.使用方法:

Scanner reader=new Scanner(System.in);

然后reader对象调用下列方法(函数),读取用户在命令行输入的各种数据类型:

 

 值得注意的是,Scanner默认的分隔符是空格。

 

 

nextByte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShort()

注:上面由next()方法转化而来,空格,TAB快结束

上述方法执行时都会造成堵塞,等待用户在命令行输入数据回车确认.

例如,拥护在键盘输入

12.34,hasNextFloat()的值是true,而hasNextInt()的值是false. NextLine()等待用户输入一个文
本行并且回车,该方法得到一个String类型的数据。相比nextLine()回车确认,按照行读为string
// 摘要自csdn

 

自己的粗浅理解是:next()方法及其子类都是将类似于指针的东西向下移动,如果读的东西和方法要求的类型不一致的话,程序会抛出异常的。

例题如下:

 1 public class ScannerExperiment {
 2      public static void main(String[] args) throws FileNotFoundException { 
 3 //         Scanner s = new Scanner("123  asda bf 12 123 nh l,sf.fl ...adafafa    lda"); 
 4 //         s.useDelimiter(" |,|\\."); // useDelimiter是添加分割符?
 5 //         while (s.hasNext()) { 
 6 //                 System.out.println(s.next()); 
 7 //         }
 8          Scanner reader = new Scanner(System.in);
 9          while(reader.hasNext())
10          {
11              System.out.println(reader.nextInt());
12          }
13  }

所以,通常来说,next()方法和hasNext()方法经常在一起连用防止出现异常。

4:其他的常用方法如下:

delimiter() 方法:返回此 Scanner 当前正在用于匹配分隔符的 Pattern。

 public static void main(String[] args) throws FileNotFoundException { 
                Scanner s = new Scanner("123 asda bf 12 123 nh l,sf.fl ...adafafa    lda"); 
//                s.useDelimiter(" |,|\\."); 
                while (s.hasNext()) { 
                        System.out.println(s.next()); 
                } 
        }

hasNext()
判断扫描器中当前扫描位置后是否还存在下一段。
hasNextLine()
如果在此扫描器的输入中存在另一行,则返回 true。
next()
查找并返回来自此扫描器的下一个完整标记(String)。
nextLine()
此扫描器执行当前行,并返回跳过的输入信息。

 

posted @ 2022-04-18 19:35  郭楠代码  阅读(103)  评论(0)    收藏  举报