Sacnner类

Scanner类

1.Scanner类是什么

通过定义一个Scanner类的对象,我们可以获取用户在键盘上的输入,实现用户和程序的交互

2.如何使用

2.1 next和hasnext
import java.util.Scanner;
public class Demo1_scanner {
     public static void main(String[] args) {
        //创建scanner类用来接受键盘输入
        Scanner scanner =new Scanner(System.in);
        System.out.println("请输入字符串1:");//hello world
        if(scanner.hasNext()){
            String str=scanner.next();//使用next接受字符
            System.out.println("你的输入1:"+str);//hello
        }

        //io流类,使用完需要释放资源
        scanner.close();
    }
}

image-20220221232503893

2.2 nextLine和hasnextLine
import java.util.Scanner;
public class Demo2_scanner {
    public static void main(String[] args) {
        //创建scanner类用来接受键盘输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入字符串2:");//hello world
        if(scanner.hasNextLine()){
            String str2 = scanner.nextLine();//使用nextLine接受字符
            System.out.println("你的输入2:" + str2);//hello world
        }
        //io流类,使用完需要释放资源
        scanner.close();
    }
}

image-20220221232615715

2.3 next和nextLine的区别

从2.1和2.2可以看到,使用next和nextLine是又区别的,同样输入的是hello world ,使用next获取的是hello,儿nextLine就是hello world,下面列出两者的区别:

(1)next(),next会过滤掉第一个有效字符之前的所有无效字符(包括空格、回车、tab等),等获取到有效字符之后,又会将有效字符之后遇到的第一个无效字符当作结束标志。因此next获取到的字符是不会有空格的,所以hello world中,hello是第一个有效字符,之后的空格就被当成了结束标志。

(2)nextLine()有扫描一整行的意思,结束标识只有代表换行的回车键,所以使用nextLine时,回车键之前的所有字符都是有效字符

2.4next和hasNext

(1)hasNext():会返回bool值,用来判断缓冲区是否还有字符,有的话就返回true

(2)next():返回的是键盘输入的值

(3)next和hasNext都可以用来输入,如果没有输入,就会阻塞程序

public class Demo2_scanner {
    public static void main(String[] args) {
        //创建scanner类用来接受键盘输入
        Scanner scanner = new Scanner(System.in);
        if(scanner.hasNextLine()){
            System.out.println("请输入字符串2:");//hello world
            String str2 = scanner.nextLine();//使用nextLine接受字符
            System.out.println("你的输入2:" + str2);//hello world
        }

        //io流类,使用完需要释放资源
        scanner.close();
    }
}

image-20220221234721052

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值