0

I'm new to Java/programming and I'm trying to write a simple program that gets an element from a list IF that element is equal to some user input. I'm using a for-loop and if-statement to achieve this but even though the user input and element matches up the programming won't print the element to screen. If someone could explain why this is not working it would be very appreciated. Cheers

public static void main(String[] args){

    ArrayList<String> names = new ArrayList<String>();
    String tempObject; 
    String findName;

    names.add("John");
    names.add("Ronny");
    names.add("Gona");
    names.add("Gina");

    Scanner Input = new Scanner(System.in);
    System.out.print("Search list for: ");
    findName = Input.nextLine();

    for (int i = 0; i < names.size(); i++){
        tempObject =  names.get(i);

        if (tempObject == findName){
            System.out.print("\n" + tempObject);
        }
    }
}

3 Answers3

1

Here you go:

if (tempObject.equals(findName)){
   System.out.print("\n" + tempObject);
}

For objects, which String is, always use method equals(), since == will compare references, not values (or what is set in equals() method - in String, it will compare the size, and then compare each char on the same place if they are equal - also, if you need, you have a method called equalsIgnoreCase - sometimes, its better to use that for user inputs).

For primitives, you will have to use ==.

Adnan Isajbegovic
  • 2,227
  • 17
  • 27
0

You should use String equals to compare two Strings for equality, not operator == which just compares the references.

Try the if statement like this:

if (tempObject.equals(findName)){...}
Genzotto
  • 1,954
  • 6
  • 26
  • 45
Sajkaan
  • 1
  • 2
0

There is difference between equality and identity, in your code above you used identity instead of equality, if you change your code (to use equality) as the below you will get what you need

if (tempObject.equal(findName)){
        System.out.print("\n" + tempObject);
}
AmjadD
  • 73
  • 1
  • 9