使用String数组的值在if语句中使用

时间:2015-01-09 12:46:01

标签: java arrays string if-statement

在这种情况下,如果用户输入数组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.");
}

1 个答案:

答案 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
相关问题