关于nextLine()未录入任何数据就被跳过执行下一语句的问题

在练习使用JDBC操作Mysql数据库时,通过下面代码完成对MySQL中一表的数据增加操作:

 do {
                System.out.println("请输入用户名");
                user = sc.nextLine();
                System.out.println("请输入密码");
                password =sc.nextInt();
                predicate.setString(1,user);
                predicate.setInt(2,password);
                int i = predicate.executeUpdate();
                if (i > 0) {
                    System.out.println("add complete");
                } else {
                    System.out.println("add error");
                }
                System.out.println("if you want continuant, input 1 ");
            } while (sc.nextInt() == 1);

但是在第二次循环后,用户名的输入被自动跳过了,从键盘输入不了任何数。

而将用户名录入的user = sc.nextLine()替换为user = sc.next();即可解决问题。原因为nextLine会将上一行输入的字符中被 while (sc.nextInt() == 1)为录入的回车或是空格字符录入,进而不等键盘输入直接执行下一步。

 

 

posted @ 2022-08-11 10:20  KaZusAzzzzz  阅读(110)  评论(0)    收藏  举报