这种方法有什么问题?

Dav*_*vid 3 java recursion tail-recursion

这是方法:

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 ; 
}
Run Code Online (Sandbox Code Playgroud)

这是此方法的可能输出(y和n是用户输入):

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
Run Code Online (Sandbox Code Playgroud)

为什么这条线的"我是蓝色的"和"我是红色的"打印出来了?为什么它们以相反的顺序打印红色,第一个输入,打印最后?

vla*_*adr 5

注意

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

应该:

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

这样,您只能在用户实际应答时Yes打印单个实例中的颜色(您不希望在用户回答时打印这些实例的颜色,在您展开递归时以相反顺序重新访问的No实例- 原因打印其他答案的相反顺序.)

还要注意,在这个特定的例子中你不需要(也不想要)递归:一旦你添加else你的方法变得尾递归,你就可以迭代地实现相同的效果.通过消除递归,您还可以消除漏洞问题,即恶意用户No无限期进入的可能性,直到您的程序最终崩溃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 ; 
    }
  }
}
Run Code Online (Sandbox Code Playgroud)