java - 将多个名称保存在字符串数组中

标签 java arrays string

问题是编写一个名为 Seyyed 的类,其中包含一个名为 seyyed 的方法。我应该在 main 方法中将一些人的名字保存在字符串数组中,并计算有多少个名字以“Seyyed”开头。我写了下面的代码。但输出却出乎意料。问题出在第 10 行,第一次打印了两次“Enter a name :”这句话。

import java.util.Scanner;

public class Seyyed {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number of names :");
        int n = in.nextInt();
        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;
    }

}

例如,当我输入 3 添加 3 个名称时,程序会重复句子“输入名称:”两次,输出如下:

Enter the number of names :3
Enter a name : 
Enter a name : 
Seyyed Saber
Enter a name : 
Ahmad Ali
There are 1 Seyyed

我可以输入 2 个姓名,而我希望输入 3 个姓名。

最佳答案

The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.

in.nextInt(); 之后,只需添加 in.nextLine(); 即可消耗输入中的额外\n 。这应该可行。

原始答案: https://stackoverflow.com/a/14452649/7621786

关于java - 将多个名称保存在字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56984655/

相关文章:

java - java中如何收集协程流?

java - 尝试使用 BufferedReader 从文本文件中读取内容以显示到 JTextArea 中

php - 如何使用正则表达式将字符串拆分为二维数组?

Python __str__ 与 __unicode__

javascript - 如何将双引号中的数组转换回 Javascript 中的原始数组

java 没有捕获 ms sql 存储过程引发错误

java - Mockito:仅使用局部变量的测试方法

java - 创建一个随机向定义的终点移动的 Java Point 数组

java - 更新游戏的两个线程?一种用于图形,一种用于游戏逻辑?

java - 使用toString打印信息