0

I'm very new to this, this being only my second project for my class. When I run this, no matter what my input is, x is always > 0. I ran the debugger and found that it increments x at both city 1 and 2, so I figured I do not have my if statements set up correctly. We were instructed to prompt the user for 3 cities, and if any are a match, we tell them. Thanks in advance!

import java.util.Scanner; public class PR2 {

public static void main(String[] args) 
{
    int x = 0;
    Scanner input = new Scanner(System.in);
    String[] City = new String[3];
    City[0] = "Orlando";
    City[1] = "New York";


    for (int i = 0; i < 3; i++)
    {
        System.out.println("Please enter a city you have visited.");
        City[i] = input.nextLine();
    }

    for (int i = 0; i < 3; i++)
    {   
        if (City[i] == City[0])
        {
            x++;
        }
        else if (City[i] == City[1])
        {
            x++;
        }
    }
    if (x > 0)
    {
        System.out.println("At least one city you have entered is a match.");
    }
    if (x == 0)
    {
        System.out.println("Sorry, none of the cities you have entered are a match.");
    }


}

}

  • Oh, and they will always match in your case because you are testing the array against itself. `City[i]` is `==` to `City[0]` **when** `i = 0`. And `City[1]` when `i` is `1`. – Elliott Frisch Jun 22 '17 at 23:37
  • Not entirely sure how my question was an "exact duplicate", but thank you for your response. – Blake Smith Jun 22 '17 at 23:40
  • It's a duplicate because you are comparing strings in the wrong way. When you use `aString == anotherString` you are saying *does the container that holds the string have the same reference as this other container that holds a string*. You should use `aString.equals(anotherString)` and now you are saying *does aString equal anotherString*. `==` is only used when you compare primitive types like `int`, `boolean`, etc. When you compare objects you always use `equals` (and a string is an object of a slightly special kind). – Matt Jun 23 '17 at 01:59

0 Answers0