斐波纳契数 - 输入

时间:2015-01-26 01:24:49

标签: java

在这个程序中,我如何不断询问用户他/她是否想要找到另一个号码?它只工作一次。我应该使用while循环吗?如何设置?我很迷惑。感谢。

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 " + x + "th Fibonacci number of " + x + " is " + calcFibNum(x));

  String answer = "Y"; 
  while (answer.equals("Y"))
  {
     System.out.println("Would you like to find the Fibonaci number of another number?(Y/N)");
     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 if (answer.equalsIgnoreCase("N"))
     System.out.println();

  }


}

}

2 个答案:

答案 0 :(得分:0)

您只需要使用continuebreak。试试这个:

while (answer.equals("Y"))
  {
     System.out.println("Would you like to find the Fibonaci number of another number?(Y/N)");
     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));
   continue; // continue your loop without executing any further statements
  }
  else if (answer.equalsIgnoreCase("N"))
     System.out.println();
     break ; // break the loop and 
  }

答案 1 :(得分:0)

这种程序流程建议使用do { ... } while();语法。您希望它迭代一次,然后在用户回答“Y'你的问题。

int x;
String answer;
do{
    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));
    System.out.println("Would you like to find the Fibonaci number of another number?(Y/N)");
    answer = in.next();
} while (answer.equalsIgnoreCase("Y"));
System.out.println();