next()和nextLine()区别

通过Scanner 类的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输出的数据。

next()和nextLine()这两种接受用户输入方式的区别:
next():

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

nextLine():
1、以Enter为结束符也就是说nextLine()方法返回的是输入回车之前的所有字符。
2、可以获得空白。
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方法接收:");
        if(scanner.hasNext()){
            //使用next方法接收
            String str = scanner.next();
            //该方法不会接收到空格,遇到空格就会停止
            System.out.println("输出内容为:"+str);

        }
        scanner.close();

    }
posted @ 2021-07-09 20:41  海风不咸  阅读(1759)  评论(0)    收藏  举报