从数组中的关键字搜索字符串

时间:2013-03-31 18:48:17

标签: java arrays

我无法弄清楚为什么这不起作用?我试图从字符串中的数组中找到关键字,并在控制台中打印数组的索引号。我已尝试使用和不使用布尔值“true”的“if”语句

public class Testing 
{
    public static void main(String[] args)
    {
    String[] keywords = new String[5];
    keywords[0] = "boat";
    keywords[1] = "car";
    String myString = "the banana car";

          for(int a = 0; a <= keywords.length; ++a)

          {

             if(myString.contains(keywords[a])== true)
                {

                System.out.println(myString.indexOf(keywords[a]));
                }
             else
                {
                System.out.println("Those keywords are not in that string"); 
                }

           }
     }
}

6 个答案:

答案 0 :(得分:4)

String[] keywords = new String[5];////////////here you have array with 5 element
    keywords[0] = "boat";
    keywords[1] = "car";
//////////you just full index 0 and index 1

然后你循环显示关键字

的长度
for (int a = 0; a <keywords.length; a++) 
//////keywords.length=5 , index 0 and index 1 have a value but the other index is empty 

所以:

  • 您需要填写关键字数组:

     keywords[0] = "boat";
     keywords[1] = "car";
     keywords[2] = //////////;
     keywords[3] = //////////;
     keywords[4] = ///////;
    
  • 或使长度= 2:

    String[] keywords = new String[2];
    

答案 1 :(得分:1)

由于您已声明String数组包含5个元素

,因此缺少3个额外元素
String[] keywords = new String[5];
    keywords[0] = "boat";
    keywords[1] = "car";

答案 2 :(得分:1)

a <= keywords.length应为a < keywords.length,如果您声明它的大小 5 ,那么您应该填充数组 5 元素(来自0到4)。

Java 中的数组为零,因此如果您有长度 n 的数组,则索引从 0 n -1 (总计 n

另一件重要的事情:

if(myString.contains(keywords[a])== true)中,== true是多余的,因为myString.contains(keywords[a])返回 true false ,此处您只想查看这个。所以删除== true是一种更好的风格。

答案 3 :(得分:1)

您尚未初步确定keywords的所有元素,因此您将获得NullPointerException

如果您只想检查初始化的前两个元素,请将for循环更改为以下内容:

for (int a = 0; a <= 1; ++a)

答案 4 :(得分:1)

这个程序:

public class Testing {

   public static void main( String[] args ) {
      String[] keywords = new String[]{ "boat", "car" }; // Only 2 not 5
      String myString = "the banana car";
      for( String keyword : keywords ) {
         int index = myString.indexOf( keyword );
         if( index > -1 ) {
            System.out.println(
               "Keyword '" + keyword + "' is in the string '" +
               myString + "' at position " + index ); 
         }
         else
         {
            System.out.println( "Keyword '" + keyword +
               "' is not in the string '" + myString + "'" ); 
         }
      }
   }
}

输出:

Keyword 'boat' is not in the string 'the banana car'
Keyword 'car' is in the string 'the banana car' at position 11

答案 5 :(得分:0)

public static void main(String[] args) {
    String[] keywords = {"boat", "car"};
    String myString = "the banana car";
    for(int i = 0; i < keywords.length; i++) {
        System.out.println(myString.contains(keywords[i]) ? myString.indexOf(keywords[i]) : "Those keywords are not in that string");

    }
}

..应该有用