java while循环第二次输入跳过的问题

图片说明图片说明

这个代码当我进入第二个while,输入n时,重新开始第一个while,
String password=sc.nextLine();这行不会卡住,会直接往下执行,求解,谢谢

你使用了sc.next()方法后,想使用 sc.nextLine()赋值给password。但是呢,在使用String password = sc.nextLine()之前需要先调用一次sc.nextLine()。

具体可以看我下面给的示例代码,你运行一次就知道了

public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String str01 = s.next();
        // 上面使用了非nextLine的方法,
        // 如果想使用nextLine(),需要先调用一次nextLine()再使用nextLine()。
        s.nextLine(); // 这行代码如果注释那么下一行输入赋值则无法进行
        String line = s.nextLine();
        System.out.println(str01);
        System.out.println(line);
    }