• Post Reply Bookmark Topic Watch Topic
  • New Topic

Ending a loop early  RSS feed

 
Eric Matthew
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a method that test whether an array's elements are all equal. The method contains a for loop to test, and if they are equal, increments a counter. But for some reason, my counter is increasing more than the times I am even testing it.



This is part of the method. There is more to it but I feel as though I'm forgetting something more trivial.
 
Tapas Chand
Ranch Hand
Posts: 614
9
BSD Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are few things you need to consider here.
What type getsuit() returns?

If it returns int then flow will never come to else, it will always break at the very first iteration.
Because for the first time, value of "y" would be "0".
So if condition will always be true for the first iteration and it will break.

If getsuit() returns String, then you need to reconsider your if statement condition.
Strings are not compared using String.equals().

If getsuit() returns any other custom object, you need to override the equals() method and implement your own.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tapas Chand wrote:Strings are not compared using String.equals().

That is exactly how Strings are compared.
 
Tapas Chand
Ranch Hand
Posts: 614
9
BSD Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bear Bibeault wrote:That is exactly how Strings are compared.

Oh what a silly mistake to make.
I was typing...Strings are compared using String.equals().
I do not know how "not" got into it.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tapas Chand wrote:

If it returns int then flow will never come to else, it will always break at the very first iteration.
Because for the first time, value of "y" would be "0".
So if condition will always be true for the first iteration and it will break.


Are you sure? Assuming getsuit() returns an int (or an Enum), and assuming the method is idempotent, then I would expect

to be false when y = 0.
 
Tapas Chand
Ranch Hand
Posts: 614
9
BSD Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike. J. Thompson wrote:Are you sure? Assuming getsuit() returns an int (or an Enum), and assuming the method is idempotent, then I would expect

to be false when y = 0.


Seriously man, I need couple of days break.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!