By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,122 Members | 1,564 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,122 IT Pros & Developers. It's quick & easy.

IF loop error?

P: 5
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.

Expand|Select|Wrap|Line Numbers
  1.  
  2. while (y == 1)
  3. {
  4. System.out.println(" ");
  5. System.out.print("Do you want to set the battleship to North, South, East, or West?");
  6. bshipnsew = EasyInput.getln();
  7. if (bshipnsew == "north")
  8. {
  9. System.out.println("NORTH");
  10. y = 0;
  11. }
  12. else if (bshipnsew == "south")
  13. {
  14. System.out.println("SOUTH");
  15. y = 0;
  16. }
  17. else if (bshipnsew == "east")
  18. {
  19. System.out.println("EAST");
  20. y = 0;
  21. }
  22. else if (bshipnsew == "west")
  23. {
  24. System.out.println("WEST");
  25. y = 0;
  26. }
  27. else System.out.println("You have selected invalidly, please retry");
  28. }
  29.  
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.
Jul 20 '07 #1
Share this Question
Share on Google+
3 Replies


prometheuzz
Expert 100+
P: 197
Only primitives should be compared for equality with the == operator, all Objects (Strings are Objects) should be compared with their equals(...) method.
Jul 20 '07 #2

P: 5
Thanks for the help, it fixed the problem.
Jul 20 '07 #3

prometheuzz
Expert 100+
P: 197
Thanks for the help, it fixed the problem.
Good to hear that, and you're welcome.
Jul 20 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.