What is 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 the output of this method is possible (y and n 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 the line "I am blue" and "I am red" printed so? Why are they printed in reverse with red, the first entered, the last printed?

+3
source share
4 answers

This simple recursion . You call CPUcolor()in yours CPUcolor()again. When the call is returned, the remaining commands of each original method will be executed.
To fix this, you must add a refund:

if (a.equals ("n") || a.equals("N"))
{
  return CPUcolor();
}
+3
source

note that

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

it should be:

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

, , Yes ( , No, , , - , .)

, ( ) : else tail-recursive, . , , , No , fooobar.com/questions/1740540/... Exception

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 ; 
    }
  }
}
+5

, , :

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

: CPUColor(). , CPUColor() , , , .

. , !

+2

Because you are calling a new CPUColor () before printing the results of this.

0
source

Source: https://habr.com/ru/post/1740540/


All Articles