Scanner类

Scanner类


使用Scanner时需要导入 java.util.Scanner


几个常用的方法

方法名 说明
hasNextXxx() 是否还有下一个输入,Xxx可以是Int、Long等基本数据类型,hasNext()判断是否还有字符串
nextXxx() 获取下一个输入,next()为获取下一个字符串
hasNextLine() 是否还有下一行
nextLine() 获取一行输入
useDelimiter(String pattern) 指定分隔符,默认以空格、tab、回车为分隔符


从键盘读取:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    while(sc.hasNextInt()) {
        System.out.println(sc.nextInt());
    }
}


从文件读取:

读取文件的时候需要导入 java.io.File 并抛出异常

 public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(new File("test.java"));

        while(sc.hasNextLine()) {
            System.out.println(sc.nextLine());
        }
    }

猜你喜欢

转载自www.cnblogs.com/yi-hui/p/8974557.html