Reputation: 51
I have a input string array (called inputArray_1) of length 3. I have another string array (called keywords) with keywords like so:
System.out.println("Input 1:");
for (int i = 0; i < inputArray_1.length; i++)
{
inputArray_1[i] = reader.nextLine();
}
String[] keywords = {"dog", "cat", "monkey", "apple"};
The output of inputArray_1 might look like this:
The dog had many friends.
So I want to check each index of the array, and see if the string's at each index has any of the keywords in it. It doesn't have to include all the keywords just one of them.
So far I have this and it is not giving me the right input.
for(int i = 0; i < inputArray_1.length; i++)
{
if(inputArray_1[i].contains(keywords[i]))
{
System.out.println("YAY");
}
else
System.out.println("BOO");
}
Upvotes: 0
Views: 1043
Reputation: 4071
Along with everyones solution, If you want to test some java 8 Stream and lambda following is the way you can do it easily
String[] keywords = {"dog", "cat", "monkey", "apple"};
Arrays.stream(inputArray_1).forEach(
input -> {
if (Arrays.stream(keywords).anyMatch(input::equals)) {
System.out.println("YAY");
} else {
System.out.println("BOO");
}
});
inputArray_1
and iterating it using forEach
keywords
array. anyMatch
here gives you the boolean value true
if it exists and false
if it not. You are the simply using that logic to print your outputsIf you feel interest about this cool Java 8 stuff. Dig this Java 8 Stream Tutorial for better understanding how the Stream API and Lambda works. And also this specific tutorial to Check if Array contains a certain value
Upvotes: 1
Reputation: 106
Assuming that inputArray_1 is a String array that results from splitting on white spaces, you would need some type of inner loop that checks the current String from the input array, against all Strings from the keywords array. So something like:
String [] inputArray_1 = new String [] {"word3","word2","word3"};
String [] keywords = new String [] {"word1","word3"};
outerloop:
for(int i = 0; i < inputArray_1.length; i++) {
for (int j = 0; j < keywords.length; j++) {
if(inputArray_1[i].equals(keywords[j])){
System.out.println("YAY");
continue outerloop;
}
}
System.out.println("BOO");
}
Upvotes: 0
Reputation: 740
If the inputArray_1
contains sentences(strings with whitespace and > 1 words), you would want to iterate through each keyword to check if the current sentence, or inputArray_1[i]
, .contains()
that keyword.
But if your inputArray_1
just contains values of single words/no sentences, then you could just have one loop like so.
//This will only work if inputArray_1 contains no sentences, just single words
for(int i = 0; i < inputArray_1 .length; i++)
{
if(keywords.contains(inputArray_1[i]))
{
System.out.println("YAY");
}
else
{
System.out.println("BOO");
}
}
Upvotes: 0
Reputation: 237
use another loop for the keywords inside the 1st loop to check every elements in the keywords list.
Upvotes: 0