• Scanner类中nextInt()和nextLine()一起使用时出现的问题


    问题引出

    当我们在编写Java程序时,想要录入一个int型的数值,并在其下方录入一个字符串类型的值。

    import java.util.Scanner;
    
    public class Demo1 {
        public static void main(String[] args) {
            // Scanner类中的nextInt()方法和nextLine()方法连用时所出现的问题
            Scanner sc = new Scanner(System.in) ;
            System.out.print("请输入一个人数字:");
            int num = sc.nextInt();
    
            System.out.print("请输入一个字符串:");
            String str = sc.nextLine();
    
            System.out.println("num = " + num);
            System.out.println("str = " + str);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在这里插入图片描述

    • 程序运行后我们在控制台输入了数值1,按下回车键表示输入结束,准备去输入字符串的值,结果程序直接结束了。看输出结果,num = 1 str = 也就是说num和str我们都进行录入了,但是明明没有输入字符串值。

    • 这是因为在我们按下回车键结束数字输入时,由于回车键是\r\n,属于字符串,而下面要录入的也刚好是字符串,系统就默认将\r\n 给了str,而nextLine() 方法解结束符也恰好为回车符,所以结束了字符串的输入。得到最后的结果就是num = 1 ; str = "" ;

    当然不单单是nextInt()方法会对nextLine()方法有影响,nextByte()、nextDouble()、nextBoolean()等以\r\n作为结束符的Scanner类中的方法都会对其产生影响

    解决方案

    解决方案一:

    将str的录入移到num的上面

    import java.util.Scanner;
    
    public class Demo1 {
        public static void main(String[] args) {
            // Scanner类中的nextInt()方法和nextLine()方法连用时所出现的问题
            Scanner sc = new Scanner(System.in) ;
            System.out.print("请输入一个字符串:");
            String str = sc.nextLine();
    
            System.out.print("请输入一个人数字:");
            int num = sc.nextInt();
    
    
            System.out.println("num = " + num);
            System.out.println("str = " + str);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述

    解决方案二(建议):

    创建不同的Scanner对象录入基本数据类型和字符串类型

    import java.util.Scanner;
    
    public class Demo1 {
        public static void main(String[] args) {
            // Scanner类中的nextInt()方法和nextLine()方法连用时所出现的问题
            Scanner sc = new Scanner(System.in) ;
            System.out.print("请输入一个人数字:");
            int num = sc.nextInt();
    
            Scanner sc1 = new Scanner(System.in) ;
            System.out.print("请输入一个字符串:");
            String str = sc1.nextLine();
    
    
            System.out.println("num = " + num);
            System.out.println("str = " + str);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在这里插入图片描述

  • 相关阅读:
    推荐十个优秀的ASP.NET Core第三方中间件,你用过几个?
    什么是API网关?为什么要用API网关?
    智能控制理论及应用 王耀南等编著
    python讲解(2)
    【计算机网络_应用层】协议定制&序列化反序列化
    详解 Springboot 中使用 Aop
    kafkaStream实时流式计算
    Rxjs TakeUntil 操作符的学习笔记
    动态切换数据源总结学习
    吐槽嫌弃测试周期太长?开发自测一下
  • 原文地址:https://blog.csdn.net/weixin_45890113/article/details/126199142