2015-01-26 4 views
0

이 프로그램에서 다른 번호를 찾으려면 계속 묻는 방법? 그것은 한 번만 작동합니다. 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(); 

    } 


} 

}

답변

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 
    } 
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(); 
+0

그것은 또한 당신의 코드가 작은 버그가 있음을 지적 가치 - 당신의'calcFibNum (x)는'방법, 당신은 어떤 입력을 확인하지 않고 당신이 스택 공간이 부족 때까지 그렇게 음수 무한 재귀 . –