zhangyaru

获取用户输入的字符串时,可以通过hasNext()和hasNextLine()来判断是否还有输入的字符串内容,通过next()和nextLine()来获取用户输入的字符串

next():空白作为结束符,不能得到空白后面的字符串

nextLine():回车作为结束符,可以获取空白

import java.util.Scanner;

public class Demo2 {


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入内容:");
        if (scanner.hasNext()) {
            String next = scanner.next();//使用next()时,如果遇到空格则默认输入结束
            System.out.println(next);

        }
        scanner.close();//不使用时关闭资源
    }

}

public class Demo2 {


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入内容:");
        if (scanner.hasNextLine()) {
            String next = scanner.nextLine();//使用nextLine()时,回车默认输入结束
            System.out.println(next);

        }
        scanner.close();//不使用时关闭资源
    }

}

scanner还有hasNextInt(),hasNextFloat(),nextInt(),nextFloat()等各种类型的用法,可进Scanner工具类查看

分类:

技术点:

相关文章: