Java中使用键盘录用【Scanner】遇到的问题

Java中使用键盘录入,尤其是通过Scanner类,有时会遇到几个常见问题,以下是一些问题及其解决方法:

一、空格截断问题:

当使用Scannernext()方法读取带有空格的字符串时,输入会在遇到空格时被截断。解决这个问题应该使用nextLine()方法来读取整行输入,包括空格。

示例代码:

Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine(); // 使用nextLine读取整行输入

二、next()、nextInt()、nextDouble()等nextXxx()与nextLine()连用、混用的问题:

问题描述:

键盘还未输入字符,代码直接跳到下一个next方法,略过了nextLine()方,导致接收到的字符串为空。

代码演示问题
 // 创建对象
        Scanner scanner = new Scanner(System.in);
        // nextInt()
        System.out.println("输入数字:");
        int i = scanner.nextInt();
        System.out.println("scanner.nextInt:"+i);
        // nextLine()
        System.out.println("输入字符串:");
        String s = scanner.nextLine();
        System.out.println("scanner.nextLine:"+s);
        // nextDouble()
        System.out.println("输入数字:");
        double d = scanner.nextDouble();
        System.out.println("scanner.nextDouble:"+s);
        // nextLine()
        System.out.println("输入字符串:");
        String s2 = scanner.nextLine();
        System.out.println("scanner.nextLine:"+s2);
        // next()
        System.out.println("输入字符串:");
        String s3 = scanner.next();
        System.out.println("scanner.next:"+s3);
        // nextLine()
        String s4 = scanner.nextLine();
        System.out.println("scanner.nextLine:"+s4);

在这里插入图片描述

问题原因:

如果在同一个Scanner实例中混用了nextXXX()方法(如nextInt()nextDouble())和nextLine(),可能会遇到意料之外的行为。这是因为nextInt()等方法不会读取换行符,导致后续的nextLine()直接读取之前留下的换行符。

解决办法:

在使用完非nextLine()方法后,添加一个额外的nextLine()来消费掉换行符。

示例代码:
// 创建对象
     Scanner scanner = new Scanner(System.in);
     // nextInt()
     System.out.println("输入数字:");
     int i = scanner.nextInt();
     System.out.println("scanner.nextInt:"+i);
     // 添加一个额外的`nextLine()`来消费掉换行符
     scanner.nextLine();
     // nextLine()
     System.out.println("输入字符串:");
     String s = scanner.nextLine();
     System.out.println("scanner.nextLine:"+s);
     // nextDouble()
     System.out.println("输入数字:");
     double d = scanner.nextDouble();
     System.out.println("scanner.nextDouble:"+s);
     // 添加一个额外的`nextLine()`来消费掉换行符
     scanner.nextLine();
     // nextLine()
     System.out.println("输入字符串:");
     String s2 = scanner.nextLine();
     System.out.println("scanner.nextLine:"+s2);
     // next()
     System.out.println("输入字符串:");
     String s3 = scanner.next();
     System.out.println("scanner.next:"+s3);
     // 添加一个额外的`nextLine()`来消费掉换行符
     scanner.nextLine();
     // nextLine()
     String s4 = scanner.nextLine();
     System.out.println("scanner.nextLine:"+s4);

在这里插入图片描述


最后

如果感觉有收获的话,点个赞 👍🏻 吧。
❤️❤️❤️本人菜鸟修行期,如有错误,欢迎各位大佬评论批评指正!😄😄😄

💘💘💘如果觉得这篇文对你有帮助的话,也请给个点赞、收藏下吧,非常感谢!👍 👍 👍在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值