2013-04-09 106 views
0

我的程序應該根據用戶輸入的內容輸出一個斐波那契數(例如,如果他們輸入7,程序將輸出13)。這部分工作。我遇到問題的部分是程序檢查以確保用戶輸入的數字是正數且小於或等於70.它應該再次要求用戶輸入,而是輸出「Fibonacci#-1爲0「並停止。這裏是我的代碼:打印斐波納契數

import java.util.Scanner; 

public class scalvert_Fibonacci 
{ 
public static void main (String args[]) 
{ 
    Scanner input = new Scanner (System.in); 

    int sum = 0; 
    int num; 
    int f1 = 0, f2 = 0, f3 = 1; 

    System.out.print("Which Fibonacci number would you like? "); 
    num = input.nextInt(); 

    if (num == 0) 
    return 0; 

    else if (num == 1) 
    return 1; 

    while (num < 0 || num > 70) 
    { 
     System.out.print("Which Fibonacci number would you like? "); 
     num = input.nextInt(); 
    } 

     for(int i = 1; i <= num; i++) 
     { 
       f1 = f2; 
       f2 = f3; 
       f3 = f1 + f2; 
     } 
     System.out.printf("Fibonacci #%d is %d\n",num, f2); 
} 
} 
+0

您的代碼還有其他問題,當返回類型爲「void」時,您不應返回任何值。你能編譯這個嗎? – JackSparrow 2013-04-09 07:58:02

回答

0

使用這可能會解決你的問題

if(num<0 || num>70) 
{ 
    //ask a number again 
} 
else 
{ 
    //calculate 
} 

or use this 

if(0 < num < 71) 
{ 
    //calculate 
} 
else 
{ 
    //ask for a valid number 
} 
+0

這確實奏效,但是當我輸入一個無效數字兩次後,它就結束了程序。另外,如果我輸入了一個無效的數字,然後是有效的數字,它仍然以無輸出結束。 – user1858350 2013-04-09 07:50:39

+0

使用返回與您的如果,**可能**解決您的問題..(我不知道它)..進一步,你可以去邊檢查有效的輸入。 – Bhavik 2013-04-09 07:54:12

+0

將if(num == 0)返回0;中? – user1858350 2013-04-09 07:55:24

0

我想通了。

while(num < 0 || num > 70) 
    { 
     System.out.print("Which Fibonacci number would you like? "); 
     num = input.nextInt(); 
    }