Scanner对象总结

狂神说Java-用户交互Scanner总结

一、next():

  • 一定要读取到有效字符后才可以结束输入。
  • 对输入有效字符之前遇到的空白,next()方法会自动将其去掉。
  • 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
  • next()不能得到带有空格的字符串。

演示代码如下:

public class Demo1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入:");
        if (sc.hasNext()) {
            //使用next方式接收
            String str = sc.next();
            System.out.println("输出:" + str);
        }
        //凡是属于IO流的类不关闭就会一直占用资源,养成好习惯记得关闭释放资源
        sc.close();
    }
}

结果:

二、nextLine():

  • 以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符。
  • 可以获得空白。
public class Demo2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入:");
        if(sc.hasNextLine()){
            //使用next方式接收
            String str = sc.nextLine();
            System.out.println("输出:" + str);
        }
        //凡是属于IO流的类不关闭就会一直占用资源,养成好习惯记得关闭释放资源
        sc.close();
    }
}

结果:

参考:https://www.bilibili.com/video/BV12J41137hu?p=33
附:java输入hasNext()和hasNextLine()方法的区别

posted @ 2021-11-17 00:19  吃辣椒会上瘾  阅读(23)  评论(0编辑  收藏  举报