Scanner部分用法

源定义代码


final 修饰:
public final class Scanner implements Iterator<String>, Closeable { }

用法

 next()读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。
 nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。

一些前提知识:
import java.util.Scanner;
NoSuchElementException(父 RuntimeException)
IllegalStateException(父 RuntimeException)
InputMismatchException(父 NoSuchElementException)
1、public Scanner(InputStream source){ },用给定的输入流创建一个Scanner对象。
例1:
Scanner in = new Scanner(System.in);
例2:
InputStream in = new FileInputStream(new File("D:\\test.java")); 
Scanner s = new Scanner(in); 
2、public String nextLine(){ },读取输入的下一行内容。(以回车作为分隔符)。

@throws NoSuchElementException if no line was found
@throws IllegalStateException if this scanner is closed

例1:
Scanner in = new Scanner(System.in);
String name = in.nextLine();
System.out.println(name);
3、public String next(){ },读取输入的下一个单词。(以空格、回车作为分隔符)。

@throws NoSuchElementException if no more tokens are available
@throws IllegalStateException if this scanner is closed

例1:
Scanner in = new Scanner(System.in);
String name = in.next();
System.out.println(name);
4、public int nextInt(){ },读取输入的下一个int类型数据。

@throws InputMismatchException,下一个数据不是int类型或是超出int类型数据范围
@throws NoSuchElementException if input is exhausted,下一个int数据不存在
@throws IllegalStateException if this scanner is closed

public static void main(String[] args) throws FileNotFoundException {	   
		 InputStream input = new FileInputStream(new File("D:\\45\\test.txt"));
		   Scanner in = new Scanner(input);
		   for(int i=0;i<4;i++) {
			     int old = in.nextInt();
		         System.out.println(old);
		   }
//文件内容为:1 2 3
//抛出异常
5、public boolean hasNext(){ },判断扫描器中当前扫描位置后是否还存在下一段。(以空格、回车作为分隔符)。

@throws IllegalStateException if this scanner is closed

 InputStream input = new FileInputStream(new File("D:\\45\\test.txt"));
		   Scanner in = new Scanner(input);
		   while(in.hasNext()){ 
               System.out.println(in.next()); 
           } 
6、public boolean hasNextLine(){ }, 判断扫描器的输入中是否存在下一行。(回车作为分隔符)。

@throws IllegalStateException if this scanner is closed

InputStream input = new FileInputStream(new File("D:\\45\\test.txt"));
		   Scanner in = new Scanner(input);
		   while(in.hasNextLine()){ 
               System.out.println(in.nextLine()); 
           } 
7、指定定界符
public Scanner useDelimiter(String pattern){}
public Scanner useDelimiter(Pattern pattern){}
8、返回作为定界符使用的 Pattern 对象
public Pattern delimiter(){}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值