我不明白为什么这不起作用?我试图从字符串中的数组中找到关键字,并在控制台中打印数组的索引号。我已经尝试过使用和不使用 boolean 值“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");
}
}
}
}
最佳答案
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
然后你在 keywords 的长度上循环
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];
关于java - 从数组中的关键字搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733143/