• 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

    在这里插入图片描述

  • 相关阅读:
    js防抖和节流
    浅析-ES6
    二叉树进程
    数字与中文大写数字互转(5千万亿亿亿亿以上的数字也支持转换)
    数据库实验二
    【面经】如何使用less命令查看和搜索日志
    java ssm在线读书与分享论坛系统
    微软 SQL 服务器被黑,带宽遭到破坏
    Java电子招投标采购系统源码-适合于招标代理、政府采购、企业采购、等业务的企业
    pytorch 学习第三天 交叉熵
  • 原文地址:https://blog.csdn.net/weixin_45890113/article/details/126199142