Java中的Scanner对象【个人回顾总结版】

Java中的Scanner对象【个人回顾总结版】

1、基本内容

可以通过Scanner工具类获取用户的输入,实现程序和人的交互。

scanner类通过next(0nextLine()方法来获取输入的字符串。
在读取前我们需要使用hasNext()/hasNextLine()判断是否还有要输入的数据。

2、使用

使用scanner类中的next()方法来获取输入的字符串
next():1、一定要读到有效字符后才可以结束输入;2、对于输入有效的字符前遇到的空白,next()方法会自动将其去掉;3、只有输入有效字符后,才将其后面输入的空白作为分隔符或者结束符;4、next()不能得到到空格的字符串

public class Demo01 {
    
    


    public static void main(String[] args) {
    
    
        /**
         * 创建一个扫描器的对象 用于接受键盘数据
         */
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方式接收:");

        /**
         * 定义str对象来接收键盘输入的数据
         * 等待用户的输入
         */
        String str = scanner.next();
        /**
         * 输入str 接收到的内容
         */
        System.out.println("输出的内容为:"+str);

        /**
         * 关闭资源
         */
        scanner.close();
    }
}

在这里插入图片描述

使用scanner类中的nextLine()方法来获取输入的字符串
nextLine():1、以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符。2、可以得到空白

public class Demo01 {
    
    


    public static void main(String[] args) {
    
    
        /**
         * 创建一个扫描器的对象 用于接受键盘数据
         */
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方式接收:");

        /**
         * 定义str对象来接收键盘输入的数据  
         * 等待用户的输入
         */
        String str = scanner.nextLine();
        /**
         * 输入str 接收到的内容
         */
        System.out.println("输出的内容为:"+str);

        /**
         * 关闭资源
         */
        scanner.close();
    }


}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/junR_980218/article/details/125090995