-2

I have this block of code here (java):

void findDistance() {

               String name1 = new String();
               Scanner s = new Scanner(System.in);
               System.out.print("Enter the name of Starting Location: ");
               name1 = s.next();
               name1 = name1.toLowerCase();
               for (int i = 0; i < numCities; i++) {
                   System.out.println(name1);
                   System.out.println(cityNames[i]);
                   if (name1 == cityNames[0]){
                   //    int x = i;
                       System.out.print("x");

                   }
                    else {
                    //     System.out.println(name1);
                    //     System.out.println(cityNames[i]);
                          System.out.println("y");
                       }

                 }

               }

for some reason, even though name1 and cityNames[0] are equal, the if statement doesnt think so. I have a couple of print statements to return the value in there to test it, and it does print as equal. Anyone have any idea why this is happening?

Szymon
  • 42,577
  • 16
  • 96
  • 114

1 Answers1

4

Change the line

if (name1 == cityNames[0]){

to

if (name1.equals(cityNames[0])){

You need to use equals() or otherwise by using == you're comparing references of the variables.

Szymon
  • 42,577
  • 16
  • 96
  • 114