1、概述
1.1 JDK提供了Scanner类,用来获取键盘输入;
1.2 Scanner类是 一个基于正则表达式的文本扫描器,可以从文件、输入流、字符串中解析出基本类型值、字符串值;
1.3 Scanner类提供了多个不同的构造器,可接受文件,输入流,字符串作为数据源,用于从文件、输入流、字符串中解析数据;
public final class Scanner implements Iterator<String>, Closeable { =====构造器 private Scanner(Readable source, Pattern pattern) { assert source != null : "source should not be null"; assert pattern != null : "pattern should not be null"; this.source = source; delimPattern = pattern; buf = CharBuffer.allocate(BUFFER_SIZE); buf.limit(0); matcher = delimPattern.matcher(buf); matcher.useTransparentBounds(true); matcher.useAnchoringBounds(false); useLocale(Locale.getDefault(Locale.Category.FORMAT)); } public Scanner(File source) throws FileNotFoundException { this((ReadableByteChannel)(new FileInputStream(source).getChannel())); } public Scanner(String source) { this(new StringReader(source), WHITESPACE_PATTERN); } public Scanner(InputStream source) { this(new InputStreamReader(source), WHITESPACE_PATTERN); } }
1.4 Scanner类提供的方法:
hasNextXX():是否还有下一项;
nextXX():获取下一项;
import java.util.Scanner; public class TestScanner { public static void main(String[] args){ boolean flag=true; while (flag){ //System.in标准输入,即键盘输入 Scanner scanner=new Scanner(System.in); String inputContent=scanner.next(); if (inputContent.equals("exit")){ flag=false; } System.out.println(inputContent); } } }
hasNextLine():是否有下一行;
nextLine():获取下一行;
原文地址:https://www.cnblogs.com/anpeiyong/p/11357153.html
时间: 2024-10-11 00:03:32