Answer the question
In order to leave comments, you need to log in
Checking if a key exists in an array. How?
Tell me please. There is an array:
String[] catsNames = {
"Васька",
"Матроскин"
};
Answer the question
In order to leave comments, you need to log in
public class Example {
private static final String[] catsNames = { "Васька", "Матроскин" };
public static boolean contains(String[] array, String value) {
for (String item : array)
if (item.equals(value))
return true;
return false;
}
public static void main(String[] args) {
String name = args[0];
if (contains(catsNames, name)) {
// В массиве содержится строка, которую пользователь
// передал первым аргументом командной строки
}
else {
// Строка не содержится в массиве
}
}
}
Java 8 guys!
public static void main(String[] args) {
String[] catsNames = new String[]{"Матроскин", "Барбос", "Пушистый п#$%рас"};
boolean contains = Arrays.stream(cats).anyMatch("Матроскин"::equals);
System.out.println(contains); //имеем true
contains = Arrays.stream(cats).anyMatch("Барбоскин"::equals);
System.out.println(contains); //имеем false
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question