Results 1 to 4 of 4
  1. #1
    aedara is offline Member
    Join Date
    Jun 2011
    Posts
    2
    Rep Power
    0

    Default Program not throwing exception

    I have written the below Fibonacci series program that accepts an integer to display that many numbers in the series. Works fine, but when you enter a negative number, it is supposed to throw the exception and instead it prints out the first number. It does throw an exception if I enter a character. Can you please help? Also, can you suggest if I am writing the program in an efficient way?

    import java.util.Scanner;
    public class Fibonacci {

    public static void main(String[] args) {
    int n, a, b, c, i;

    try{
    System.out.println("Please enter the number of fibonacci series you would like to print");
    Scanner input = new Scanner(System.in);
    n = input.nextInt();
    while (n == 0) {
    System.out.println("please enter a number greater than zero");
    n = input.nextInt();
    }
    a = 1;
    b = 1;
    System.out.println(a);
    for(i = 2; i<=n; i++){
    System.out.println(b);
    c = a + b;
    a = b;
    b = c;
    }

    } catch(Exception E){
    System.err.println("You did not enter a valid integer number");
    }


    }

    }

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,395
    Blog Entries
    7
    Rep Power
    25

    Default

    Quote Originally Posted by aedara View Post
    while (n == 0) {
    Suppose n < 0 (as you told us).

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  3. #3
    aedara is offline Member
    Join Date
    Jun 2011
    Posts
    2
    Rep Power
    0

    Default

    That is true..if n < 0, it should throw an exception, but it is not. Do you know why?

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,807
    Rep Power
    10

    Default

    Do you want the JVM to read your mind? How is it supposed to know that if n < 0 to throw an exception if you do not tell it to do so?

Similar Threads

  1. Exception throwing
    By andy16 in forum New To Java
    Replies: 9
    Last Post: 06-07-2010, 05:57 PM
  2. Replies: 11
    Last Post: 11-05-2009, 01:44 PM
  3. Main method throwing specific Exception
    By bugger in forum New To Java
    Replies: 5
    Last Post: 05-13-2009, 02:34 PM
  4. Display Message Without Throwing Exception
    By kailashchandra in forum JavaServer Faces (JSF)
    Replies: 0
    Last Post: 09-27-2008, 09:05 AM
  5. throwing Exception
    By bugger in forum New To Java
    Replies: 3
    Last Post: 11-09-2007, 10:35 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •