1

In this case, if the user enters any one of the values available in the array fruits, I want the if statement to come true, however I don't understand how to accomplish that.

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.");
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Daki
  • 35
  • 7
  • possible duplicate of [In Java, how can I test if an Array contains a certain value?](http://stackoverflow.com/questions/1128723/in-java-how-can-i-test-if-an-array-contains-a-certain-value) – Erik Jan 09 '15 at 12:54
  • 1
    Arrays.asList(fruits).contains(input) will work for you :) – Parth Soni Jan 09 '15 at 12:56
  • You need a loop to traverse in the array searching for user input if it matches –  Jan 09 '15 at 12:56
  • 1
    Thanks everyone, I got it to work using Arrays.asList(fruits).contains(input) as Parth suggested. I have no idea how it works, since I've just started learning Java, but it works. – Daki Jan 09 '15 at 13:06

1 Answers1

1

The easiest way to accomplish this is to convert the array to a List an use the contains method:

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.");
}

However, this will probably have pretty lousy performance. Converting it to a HashSet should take care of that:

Set<String> fruits = 
    new HashSet<>(Arrays.asList("Apple", "apple", "Banana", "banana", "Orange", "orange"));
// rest of the code unchanged
Mureinik
  • 297,002
  • 52
  • 306
  • 350