首页 > 其他 > 详细

Scanner对象

时间:2021-07-24 00:05:02      阅读:16      评论:0      收藏:0      [点我收藏+]

语法:

Scanner s = new Scanner(System.in);

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

next方法:

        //创建一个扫描器对象,用于接收键盘数据
        Scanner scanner = new Scanner(System.in);

        System.out.println("使用next方式接受:");
        //判断是否有字符串
        if (scanner.hasNext()) {
            //使用next方法接收
            String str = scanner.next();
            System.out.println("输出内容为:" + str);
        }
        scanner.close();

nextLint方法:

public class Demo01 {
    public static void main(String[] args) {
        //创建一个扫描器对象,用于接收键盘数据
        Scanner scanner = new Scanner(System.in);

        System.out.println("使用nextLine方式接受:");

        if (scanner.hasNextLine()) {
            String str = scanner.nextLine();
            System.out.println("输出内容为:" + str);
        }
        scanner.close();
    }
         

这两种方法的区别:

next:

1、一定要读取到有效字符才可以结束输出

2、对输入有效字之前遇到的空白,next()方法会自动将其关掉

3、只有输入有效字符才将其后面输入的空白作为分隔符或结束符

4、next()不能得到带有空格的字符串

nextLine():

1、以Enter为结束符,也就是说nextLine方法返回的是输入的回车之前的所有字符。

2、可以获得空白

 

Scanner对象

原文:https://www.cnblogs.com/mushang/p/15050332.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!