4 回答

TA贡献1844条经验 获得超8个赞
当您按下回车键时出现问题,这是一个换行符 \n 字符。nextInt() 仅使用整数,但它会跳过换行符 \n。要解决这个问题,您可能需要在读取 int 后添加一个额外的 input.nextLine(),它可以消耗 \n。
在刚刚in.nextInt();
添加in.nextLine();
以消耗输入中的额外 \n 之后。这应该工作。
原答案: https://stackoverflow.com/a/14452649/7621786

TA贡献1946条经验 获得超4个赞
当您输入数字时,您还按下了 Enter 键,这将执行一个“\n”输入值,该值由您的第一个 nextLine() 方法捕获。为防止这种情况,您应该在代码中插入 nextLine() 以在读取 int 值后使用“\n”字符。
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
同一问题的好答案:https ://stackoverflow.com/a/7056782/4983264

TA贡献1876条经验 获得超7个赞
nextInt() 将消耗整数的所有字符,但不会触及行尾字符。所以当你在循环中第一次调用 nextLine() 时,它会读取前一个 scanInt() 留下的 eol,所以基本上读取一个空字符串。要修复此问题,请在循环之前使用 nextLine() 来清除扫描仪或对字符串和整数使用不同的扫描仪。

TA贡献2036条经验 获得超8个赞
试试这个:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
添加回答
举报