What's wrong with my Fibonacci code?
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

Could someone help me fix my code for Fibonacci? I know there's lots of Java solutions online, but please fix this code so I can see what was wrong.

import java.io.*;

class Fibonacci {
  public static void main(String args[]) {

    System.out.println('How many Fibonacci numbers do you want?');

    InputStreamReader sr = new InputStreamReader(System.in);
    BufferedReader br    = new BufferedReader(sr);

    try {
      String input = br.readLine();
      int n = Integer.valueOf(input).intValue();
      fibonacci(n);
    } catch (NumberFormatException e){
      System.out.println("That's not a number!")
    } catch (IOException) {
      System.out.println("No input received");
    }
  }

  public static void fibonacci(int n){
    int a=1,b=0;

    for (int i=0;i<n;i++){
      System.out.println(a);
      a=a+b;
      b=a-b;
    }
  }
}
awarded to alex
Tags
java

Crowdsource coding tasks.

1 Solution

Winning solution

Dear @bevan,
Assuming the file was named Fibonacci.java (because this would cause problems if it wasn't), there are 4 problems with your code.

  • On line 3, you should have public in front of class Fibonacci.
  • On line 6, double quotes " should be used instead of single quotes '.
  • On line 16, you forgot the semi-colon(;)
  • On line 17, you should have an e after IOException so it would look like this: catch (IOException e)

Here is how your code should look like:

import java.io.*;

public class Fibonacci {
    public static void main(String args[]) {

        System.out.println("How many Fibonacci numbers do you want?");

        InputStreamReader sr = new InputStreamReader(System.in);
        BufferedReader br    = new BufferedReader(sr);

        try {
            String input = br.readLine();
            int n = Integer.valueOf(input).intValue();
            fibonacci(n);
        } catch (NumberFormatException e){
            System.out.println("That's not a number!");
        } catch (IOException e) {
            System.out.println("No input received");
        }
    }

    public static void fibonacci(int n){
        int a=1,b=0;

        for (int i=0;i<n;i++){
            System.out.println(a);
            a=a+b;
            b=a-b;
        }
    }
}