-2

I'm kinda new to programming, but I can't figure out how to use a String Scanner to see if it is present in an Array (If Array contains "Apple" and the Scanner returns "Apple", Print "Present"). I'm using Eclipse Mars 4.5.0, and the code I have up to now is as follows:

public static void main(String[] args) {


    String answer = "null"; //Initialize "answer"
    String[] Fruit;         //Array of Strings called "Fruit"
    Fruit = new String[10]; //"Fruit" has 10 spaces
    //Strings saved in "Fruit":
    Fruit[0] = "Apple";
    Fruit[1] = "Banana";
    Fruit[2] = "Mango";
    Fruit[3] = "Pear";

    //The actual programme:
    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter a fruit:");
    answer = input.next();
                                                            //If the answer is 'Fruit[0]'
    if (answer == Fruit[0] || answer == Fruit[1] ||         //OR 'Fruit[1]' OR etc,
        answer == Fruit[2] || answer == Fruit[3]) {         //Print "available"
        System.out.println("This fruit is available.");
    }
                                                            //If the answer isn't 'Fruit[0]'
    else if (answer != Fruit[0] && answer != Fruit[1] &&    // AND not 'Fruit[1]' AND not
            answer != Fruit[2] && answer != Fruit[3]){      //etc, Print "not available"
        System.out.println("This fruit is not available right now.");
    }
}

However, it always returns "not available", same goes for a While-loop: it somehow doesn't seem to check whether it is even present in the Arraylist or not.

Does anybody know how to fix this? I'd love to know because I couldn't find any similar question anywhere on the internet.

EDIT: Odd, I searched for it quite a number of times, guess I missed one, sorry for duplicating!

G. Heiden
  • 1
  • 1
  • You can't compare **Strings** using **==** operator instead you have to use **equals** method of the String class for String comparison. Alsoyou don't need to evaluate any condition in else part. – Nishesh Pratap Singh Nov 21 '17 at 12:31
  • And read about java naming conventions - variable names go camelCase. – GhostCat Nov 21 '17 at 12:31

1 Answers1

0

instead of using

if (answer == Fruit[0] || answer == Fruit[1] ||         //OR 'Fruit[1]' OR etc,
        answer == Fruit[2] || answer == Fruit[3])

use:

if (TextUtils.equals(answer,Fruit[0]) || TextUtils.equals(answer,Fruit[1]) ||         
        TextUtils.equals(answer,Fruit[2]) || TextUtils.equals(answer,Fruit[3]))

Strings are always compared with equals method not by == method

Sara Tirmizi
  • 417
  • 4
  • 10