【问题标题】:How to only output words that start with "b" from an array如何仅从数组中输出以“b”开头的单词
【发布时间】:2019-04-25 04:56:12
【问题描述】:

我创建了一个允许用户输入 5 个单词的程序。这些字 存储到字符串数组中。当用户完成时,会显示以字母“B”开头的单词的输入次数,小写或大写。现在我还要重述B字。

所以这是我到目前为止的代码,它可以找到输入的单词中有多少以“b”开头

int fromIndex = 0;
    int count = 0;
    String words[] = new String [5];

    for (int x = 0 ; x <= words.length - 1 ; x = x + 1)
    {
        System.out.print ("Please enter a word: ");
        words [x] = kbi.readLine ();
        fromIndex = 0;
        words [x] = words [x].toLowerCase ();


        fromIndex = words [x].indexOf ("b", fromIndex);
        if (fromIndex == 0) // STARTS WITH B
        {
            count++;

        }

    }

    System.out.println ("You entered " + count + " 'B' words and they were: ");

我在想我可以使用 if 语句来打印 b 字。喜欢:

if (words.charAt(0) == "b")
{
    System.out.println (words);
} 

但这似乎并没有真正奏效,我真的不认为它会,我有点不知所措。

希望我能在这方面得到一些帮助,提前谢谢你。

【问题讨论】:

  • char 文字用单引号括起来:'b'
  • 可以试试String::startsWith

标签: java arrays regex string for-loop


【解决方案1】:

在您的代码中不是一个字符串(它是一个字符串数组),因此它没有您在上面使用的 charAt 方法。你的单词数组中有 5 个字符串,所以如果你想在数组中写入所有以字符 'b' 开头的字符串,你应该遍历你的数组并打印所有以 'b' 开头的字符串,如下所示:

for(String str : words){
    if (str.charAt(0) == 'b'){
            System.out.println(str);
}

一些提示: 在 java 7 中,String 具有可以使用的 startsWith 方法。如果您使用的是 java 6,请检查它是否也有:

for(String str : words){
        if (str.startsWith("b", 0)){
            System.out.println(str);
    }

【讨论】:

    【解决方案2】:

    这是因为charAt 返回char 而不是String,所以您必须更改比较:

    if (words.charAt(0) == 'b')
    

    其他可能性是使用正则表达式 "b.*" 或更简单 - String 带有 startsWith 方法,所以你可以简单地这样做:

    if (words.startsWith("b"))
    

    【讨论】:

      猜你喜欢
      • 2020-03-16
      • 2011-04-06
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      相关资源
      最近更新 更多