Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats wrong with this method?

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?

like image 902
David Avatar asked Mar 14 '26 08:03

David


1 Answers

Note that

    if (a.equals ("n") || a.equals("N"))
        {CPUcolor() ;} 
    System.out.println ("I am "+s) ;

should be:

    if (a.equals ("n") || a.equals("N"))
        {CPUcolor() ;} 
    else
        {System.out.println ("I am "+s) ;}

This way you only print the color in the single instance when the user actually answered Yes (you do not want to print the color for those instances when the user answered No, instances which you revisit in reverse order as you unwind your recursion -- the reason for the reverse order in which the other answers were printed.)

Also note that you do not need (nor want) recursion in this particular example: once you add the else your method becomes tail-recursive, and you can achieve the same effect iteratively. By eliminating recursion you also eliminate a vulnerability problem, that is, the possibility of a malicious user entering No indefinitely until your program eventually crashes with a StackOverflowException:

public static String CPUcolor () 
{ 
  while (true) {
    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 ("y") || a.equals("Y")) {
      System.out.println ("I am "+s) ;
      return s ; 
    }
  }
}
like image 152
vladr Avatar answered Mar 16 '26 20:03

vladr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!