允许用户继续输入数字,直到他们选择退出

Allow the user to continue entering numbers until they choose to quit

本程序的objective是计算第n个斐波那契数列。如何允许用户继续输入数字直到他们选择退出?谢谢。

public class FibonacciNUmbers
 {

 public static int calcFibNum(int x)
 {
  if (x == 0)
    return 0;
  else if (x == 1)
    return 1;
  else
    return calcFibNum(x-1) + calcFibNum(x-2);
 }

 public static void main(String[] args)
 {
  Scanner in = new Scanner(System.in);
  System.out.println("What number would you like to find the Fibonacci number for?");
  int x = in.nextInt();
  System.out.println("The Fibonacci number of " + x + " is " + calcFibNum(x));

  System.out.println("Would you like to find the Fibonaci number of another number?");
  String answer = in.next();
  if (answer.equalsIgnoreCase("Y"));
  {
      System.out.println("What number would you like to find the Fibonacci number for?");
      x = in.nextInt();
      System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
  }

  else 
  {
    System.out.println();
  }

}

}

顺便说一句,您的代码打印所有斐波那契数直到 n,而不是第 n 个 number.Below 只是如何从扫描仪输入输入的示例。用它来构建你想做的事情:

int num = 0;
while (in.hasNextInt()) {
num = in.nextInt();
}

编码愉快!

//start your while loop here
while (true)
{
    System.out.println("Would you like to find the Fibonacci number of another number?");
    String answer = in.next();
    if (answer.equalsIgnoreCase("Y"));
    {
        System.out.println("What number would you like to find the Fibonacci number for?");
        x = in.nextInt();
        System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
    }
    else 
    {
      System.out.println("Thanks for playing");
      break; // ends the while loop.
    }
}

当您可以计算事物或拥有一组事物时,可以使用 For 循环。当您不确定它会持续多长时间,或者如果您希望它继续直到发生某些事件(例如用户按下某个字母)时,可以使用 While 循环

上面的细微变化可能更优雅:

String answer = "Y";
//start your while loop here
while (answer.equals("Y")) {
    System.out.println("Would you like to find the Fibonacci number of another number?");
    answer = in.next(); //declare your variable answer outside the loop so you  can use it in the evaluation of how many times to do the loop.
    if (answer.equalsIgnoreCase("Y"));
    {
        System.out.println("What number would you like to find the Fibonacci number for?");
        x = in.nextInt();
        System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
    }
    else 
    {
        System.out.println("Thanks for playing");
        // no need to break out.
    }
}