我在下面有一个Java程序。起初,我试图输入 n 如下
int n = sc.nextInt();
但输出与预期不同。它运行第一次迭代而不采用用户名。更改为后
int n = Integer.parseInt(sc.nextLine());
它工作正常。"int n = sc.nextInt();"有什么问题?
public class StringUserNameChecker {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Number of usernames you want to enter
int n = Integer.parseInt(sc.nextLine());
while (n-- != 0) {
String userName = sc.nextLine();
System.out.println("Your username is " + userName);
}
}
}
当sc.nextLine()
在sc.nextInt()
后使用时,它会在整数输入后读取换行符。
因此,要正确运行代码,您必须在 sc.nextInt()
之后使用 sc.nextLine()
,如下所示:
int n = sc.nextInt();
sc.nextLine();
while(n-- > 0) {
String username = sc.nextLine();
}