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

时间:2015-01-18 02:18:38

标签: java recursion

该程序的目标是计算第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();
  }

}

}

2 个答案:

答案 0 :(得分:2)

顺便说一下,你的代码打印所有斐波纳契数字,最多为n而不是第n个数字.Below只是如何继续从扫描仪输入输入的一个例子。用它来建立你想做的事情:

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

快乐的编码!

答案 1 :(得分:1)

//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循环。当您不确定可能会持续多长时间时,或者如果您希望循环直到某些事件发生(例如,用户按某个字母),则会使用循环

上面的轻微变化可能会更加优雅:

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.
    }
}