IF loop error?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • noideanoclue
    New Member
    • Jul 2007
    • 5

    #1

    IF loop error?

    I am writing a Battleship 'Game' in Java as part of familiarizing myself with the language, but have run into a problem which I can't solve, for some inexplicable reason one of my if loops isn't working as it should, I have no idea what the problem is and would appreciate some help.

    Code:
     
    while (y == 1)
    {
    System.out.println(" ");
    System.out.print("Do you want to set the battleship to North, South, East, or West?");
    bshipnsew = EasyInput.getln();
    if (bshipnsew == "north")
    {
    System.out.println("NORTH");
    y = 0;
    }
    else if (bshipnsew == "south")
    {
    System.out.println("SOUTH");
    y = 0;
    }
    else if (bshipnsew == "east")
    {
    System.out.println("EAST");
    y = 0;
    }
    else if (bshipnsew == "west")
    {
    System.out.println("WEST");
    y = 0;
    }
    else System.out.println("You have selected invalidly, please retry");
    }
    bshipnsew is a string.

    The problem is that even if you input a valid string, like "north" it will take you to the last else in the loop.
  • prometheuzz
    Recognized Expert New Member
    • Apr 2007
    • 197

    #2
    Only primitives should be compared for equality with the == operator, all Objects (Strings are Objects) should be compared with their equals(...) method.

    Comment

    • noideanoclue
      New Member
      • Jul 2007
      • 5

      #3
      Thanks for the help, it fixed the problem.

      Comment

      • prometheuzz
        Recognized Expert New Member
        • Apr 2007
        • 197

        #4
        Originally posted by noideanoclue
        Thanks for the help, it fixed the problem.
        Good to hear that, and you're welcome.

        Comment

        Working...