string - A Java method to return one and then the other of two repeatedly -


the method want define return string of "black" or "white". going use in board game main method.

first time returns "black". second time returns "black". third time returns "white", , fourth time returns "white".

then, returns "black", "white", "black", "white", , on, repeatedly.

how may implement this?

i going define node class of string, create 2 nodes next , prev field pointing each other, , return this._next._getdatum(); not think work, , makes code complicated.

do have suggestions accomplishing this?

in order return different thing each time, method needs keep state. in java, state kept using instance variables or class variables. not knowing design, here short implementation flip-flops between "black" , "white":

public class flipflop {     boolean iswhite;     public string getcurrent() {         iswhite = !iswhite;         return iswhite ? "white" : "black";     } } 

now calling getcurrent alternate between "black" , "white":

static void main(string[] args) {     flipflop ff = new flipflop();     (int = 0; != 10 ; i++) {         system.out.println(ff.getcurrent());     } } 

here demo on ideone.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -