2015-01-09 42 views
1

在這種情況下,如果用戶輸入數組fruits中的任何一個可用值,我希望if語句來true,但我不明白如何做到這一點。使用字符串數組的值在if語句中使用

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

的可能重複(http://stackoverflow.com/questions/1128723/在-java-how-can-i-test-if-an-array-contains-a-certain-value) – Erik

+1

Arrays.asList(fruits).contains(input)will for you :) – Parth

+0

你需要一個循環來遍歷數組搜索用戶輸入,如果匹配 – Arvind

回答

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應採取照顧:?在Java中,我怎麼能測試一個數組包含一定值]

Set<String> fruits = 
    new HashSet<>(Arrays.asList("Apple", "apple", "Banana", "banana", "Orange", "orange")); 
// rest of the code unchanged 
相關問題