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.");
}
4
  • possible duplicate of In Java, how can I test if an Array contains a certain value? Commented Jan 9, 2015 at 12:54
  • 1
    Arrays.asList(fruits).contains(input) will work for you :) Commented Jan 9, 2015 at 12:56
  • You need a loop to traverse in the array searching for user input if it matches Commented Jan 9, 2015 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. Commented Jan 9, 2015 at 13:06

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.