Guest User

Untitled

a guest
Dec 14th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. package AufgabenBiel;
  2.  
  3. import javakara.JavaKaraProgram;
  4.  
  5. public class Fibonnaci extends JavaKaraProgram{
  6.     /**
  7.      * @param args
  8.      */
  9.     public static void main(String[] args) {
  10.         // TODO Auto-generated method stub
  11.         Fibonnaci obj = new Fibonnaci();
  12.         obj.run();
  13.     }
  14.    
  15.     public void myMainProgram() {
  16.         // Initialize the Message text
  17.         String text = "";
  18.  
  19.         // Calculate the fibonacci numbers for 1 to 10 and append them to the text variable
  20.         for (int i=1; i<=10; i++) {
  21.             try {
  22.                 text = text + "Fib("+i+")"+"="+ fibonacci(i) + "\n";
  23.             } catch (Exception e) {
  24.                 // Print the error Message if something goes wrong
  25.                 // (It should not go wrong as long as you don't change the program)
  26.                 tools.showMessage(e.getMessage());
  27.             }
  28.         }
  29.         // Show all calculated fibonacci numbers
  30.         tools.showMessage(text);
  31.     }
  32.    
  33.     public int fibonacci(int n) throws Exception {
  34.         // Calculates the Fibonacci number for n
  35.         if (n < 1) {
  36.             // Throw an exception if function is not defined
  37.             throw new Exception("This function is not defined for values less than one.");
  38.         }
  39.         if (n==1 || n==2) {
  40.             // Function is defined as being 1 for values 1 and 2
  41.             return 1;
  42.         }
  43.         else {
  44.             // Recursively calculate the value
  45.             int x = fibonacci(n-1)+fibonacci(n-2);
  46.             return(x);
  47.         }
  48.     }
  49. }
Add Comment
Please, Sign In to add comment