Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package AufgabenBiel;
- import javakara.JavaKaraProgram;
- public class Fibonnaci extends JavaKaraProgram{
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Fibonnaci obj = new Fibonnaci();
- obj.run();
- }
- public void myMainProgram() {
- // Initialize the Message text
- String text = "";
- // Calculate the fibonacci numbers for 1 to 10 and append them to the text variable
- for (int i=1; i<=10; i++) {
- try {
- text = text + "Fib("+i+")"+"="+ fibonacci(i) + "\n";
- } catch (Exception e) {
- // Print the error Message if something goes wrong
- // (It should not go wrong as long as you don't change the program)
- tools.showMessage(e.getMessage());
- }
- }
- // Show all calculated fibonacci numbers
- tools.showMessage(text);
- }
- public int fibonacci(int n) throws Exception {
- // Calculates the Fibonacci number for n
- if (n < 1) {
- // Throw an exception if function is not defined
- throw new Exception("This function is not defined for values less than one.");
- }
- if (n==1 || n==2) {
- // Function is defined as being 1 for values 1 and 2
- return 1;
- }
- else {
- // Recursively calculate the value
- int x = fibonacci(n-1)+fibonacci(n-2);
- return(x);
- }
- }
- }
Add Comment
Please, Sign In to add comment