0

I'm creating an Address Book program using array. I've done with the add and print data option. But now I'm stuck with the search/update option. This is my code in searching for the element if it exist in my array or not.

public void update_data(){
    String user_input_data;
    int search_data = 0;
    System.out.println("Enter the data that you want to search: ");
    user_input_data = user_data.nextLine();
    while(search_data<data_recorded){
        if(user_input_data == AddressBook_Array_name[search_data])
        {
            System.out.println("Data found!");
        }
        else
        {
            System.out.println("Data not found!"); 
        }
        search_data++;
    }
}

But when I run the program. It always return to false and print the else statement. I don't know what's wrong with it. Anyway the data_recorded variable holds the number of data inputted by the user in the add option.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Z'K
  • 29
  • 9

2 Answers2

1

You need to use equals() instead of == in java for comparision.

if (user_input_data.equals(AddressBook_Array_name[search_data]))

Also, instead of the while you may want to use the foreach loop (removes the need for search_data variable).

for(String addressBookElem : AddressBook_Array_name) {
   if (user_input_data.equals(addressBookElem)) {
     System.out.println("Data found!");
     return;
   }
}
System.out.println("Data not found!"); // reaches this statement if data not present
nitishagar
  • 9,038
  • 3
  • 28
  • 40
0

i think you should use .equals function instead of ==.