Here’s the method:
public static String CPUcolor ()
{
System.out.println ("What color am I?") ;
String s = getIns() ;
System.out.println ("are you sure I'm "+s+"? (Y/N)") ;
String a = getIns() ;
while (!((a.equals ("y")) || (a.equals ("Y")) || (a.equals ("n")) || (a.equals ("N"))))
{
System.out.println ("try again") ;
a = getIns () ;
}
if (a.equals ("n") || a.equals("N"))
{CPUcolor() ;}
System.out.println ("I am "+s) ;
return s ;
}
here is a possible output of this method (y’s and n’s are user inputs):
What color am I? red are you sure I'm red? (Y/N) N What color am I? blue are you sure I'm blue? (Y/N) N What color am I? Yellow are you sure I'm Yellow? (Y/N) y I am Yellow I am blue I am red
Why is it that the line’s “I am blue” and “I am red” printed? Why are they printed in reverse order with red, the first entered, printed last?
That’s simple recursion. You are calling
CPUcolor()within yourCPUcolor()again. When the call returns, the remaining commands of each original method will be executed.To fix it you have to add a return: