scanner类,next()和nextline()区别

发布时间 2023-07-22 14:09:45作者: 咕嘎咕咕

scanner类是获取用户的输入

Scanner s = new Scanner(system.in);

区分next()和 nextline()

public class Demo01 {
    public Demo01() {
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入内容:");
        if (scanner.hasNext()) {
            String str = scanner.next();
            System.out.println("输出的内容为:" + str);
        }

        scanner.close();
    }
}

输入: Hello World!

输出的内容为:Hello

public class Demo02 {
    public Demo02() {
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方式接收:");
        if (scanner.hasNextLine()) {
            String str = scanner.nextLine();
            System.out.println("输出的内容为:" + str);
        }

        scanner.close();
    }
}

输入:Hello World!

输出的内容为: Hello World!

 

next():碰到空格会自动去除后面

nextline():敲回车前都能输出