在这种情况下,如果用户输入数组fruits
中可用的任何一个值,我希望if
语句来true
,但我不明白要做到这一点。
import java.util.Scanner;
public class Strings {
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
String[] fruits = {"Apple", "apple", "Banana", "banana", "Orange", "orange"};
System.out.println("Enter a name of a fruit: ");
String input = Scan.nextLine();
if(/*input = any one of the values in Array fruits*/){
System.out.println("Yes, that's a fruit");
}
else{
System.out.println("No, that's not a fruit.");
}
答案 0 :(得分:1)
实现此目的的最简单方法是将数组转换为List
并使用contains
方法:
List<String> fruits =
Arrays.asList("Apple", "apple", "Banana", "banana", "Orange", "orange");
System.out.println("Enter a name of a fruit: ");
String input = Scan.nextLine();
if(fruits.contains(input) {
System.out.println("Yes, that's a fruit");
}
else{
System.out.println("No, that's not a fruit.");
}
然而,这可能会有相当糟糕的表现。将其转换为HashSet
应该注意:
Set<String> fruits =
new HashSet<>(Arrays.asList("Apple", "apple", "Banana", "banana", "Orange", "orange"));
// rest of the code unchanged