1

I'm new to java and was trying to do this program. Basically entering 3 numbers, it will calculate the volume of a cube. If a negative number is typed then it will throw an exception, and also when there are more then 3 input. I wanted it to throw an exception also, if the input is not a number, but I have no idea how to store the input inside a variable and then check if it's a string and eventually throw an exception. Any suggestions? Here's my code

     public class CubeVolume
     {
       public static void main(String [] args)
       {
         try
         {
           // try if there is more than 3 arguments 
           int width = Integer.parseInt(args[0]);
           int depth = Integer.parseInt(args[1]);
           int hight = Integer.parseInt(args[2]);
           if (args.length > 3)
           throw new ArrayIndexOutOfBoundsException
                 ("You have supplied " + args.length + " arguments!");

          // try if there is less than 3 arguments
          if (args.length < 3)
          throw new ArrayIndexOutOfBoundsException
              ("You have supplied " + args.length + " arguments!");                    

          // checks if the width entered is equal or less than 0
          if (width <= 0)
          throw new NumberFormatException
              ("The argument " + width + " is a negative number!");

          // checks if the depth entered is equal or less than 0
          if (depth <= 0)
          throw new NumberFormatException
              ("The argument " + depth + " is a negative number!"); 

          // checks if the hight entered is equal or less than 0
          if (hight <= 0)
          throw new NumberFormatException
              ("The argument " + hight + " is a negative number!");     


          int volume = width * depth * hight;
          System.out.println("The volume of a cube with dimensions " + "(" + width 
                             + "," + hight + "," + depth + ") " + "is " + volume);
         } // try

        // if there's one than more argument error will be displayed
        catch (ArrayIndexOutOfBoundsException exception)
        {
          System.out.println("Please supply width, depth and hight arguments!");
          System.out.println("Exception message was: '" + exception.getMessage() 
                             + "'");
          System.err.println(exception);
        } // catch          

       // if a negative number is entered error will be displayed
       catch (NumberFormatException exception)
       {
         System.out.println("Dimensions for a cube can't be negative, please "
                                   + "insert only positive whole numbers!");
         System.out.println("Exception message was: '" + exception.getMessage() 
                                   + "'");     
         System.err.println(exception);
       } // catch

     } // main
  } // CubeMain       
user3353167
  • 782
  • 2
  • 16
  • 31
  • After glancing at the code I don't see any obvious errors. What problems are you having, specifically? Have you tried running it? – jgitter Feb 25 '14 at 21:16
  • there's no problem, but I want to throw an exception if the input is not a number. So if it's a string would display an error message saying that is not possible to use a string, and I have no clue how to do it. – user3353167 Feb 25 '14 at 21:18
  • 1
    If you look at the spec, Integer.parseInt throws a NumberFormatException if the string does not contain a parsable integer. The only question would be whether you wanted to check for "junk" after the number, I think. – Hot Licks Feb 25 '14 at 21:20
  • Integer.parseInt() throws an exception for you if the string is not an integer. You can catch it and throw your own custom exception if you want. Side note: You're checking that the length is 3 after having already accessed the 3rd argument. – JB Nizet Feb 25 '14 at 21:21
  • How can i take the input from the console and check if it's not a number and throw an exception? because with that code if I enter a string, it will throw an exception giving the message: Dimensions for an object can't be negative, please insert only positive whole numbers! java.lang.NumberFormatException: For input string: "ciao" Exception message was: 'For input string: "ciao"' – user3353167 Feb 25 '14 at 21:36
  • You have some fundamental misunderstandings. First, look at what [`parseInt`](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)) actually does. Because it *already* throws an `Exception` (`NumberFormatException`), you don't need to throw your own. Just catch it and print the exception. – MirroredFate Feb 25 '14 at 22:28
  • You can check for negative numbers after you actually do the parsing- and you don't want to throw a `NumberFormatException`, you would want to make something like a [`NegativeNumberException`](http://aleph0.clarku.edu/~djoyce/cs101/Resources/Savitch/ch08/NegativeNumberException.java) – MirroredFate Feb 25 '14 at 22:29

2 Answers2

3

This:

int width = Integer.parseInt(args[0]);

already throws a NumberFormatException if the String in question is not a valid string representation of an integer.

EDIT:

To address your comments:

public class CubeVolume {
   private int width;
   private int depth;
   private int height;

   public static void main(String [] args) {
       if (args.length != 3) {
           throw new Exception("Width, height and depth are required arguments");
       }
       width = Integer.parseInt(args[0]);
       depth = Integer.parseInt(args[1]);
       height = Integer.parseInt(args[2]);

       // more stuff here
   }
}
jgitter
  • 3,396
  • 1
  • 19
  • 26
  • is it possible to do throw a custom exception? – user3353167 Feb 25 '14 at 21:21
  • 1
    Also, I highly recommend that you don't "repurpose" existing java exceptions. Either throw generic Exceptions or create new specific exception classes. – jgitter Feb 25 '14 at 21:21
  • Yes, it is possible to throw custom exceptions. Just create a class that extends Exception. .... Then throw it. – jgitter Feb 25 '14 at 21:22
  • if I run it and let's say i type 'hello' into the console, it will catch the exception for the negative numbers, so it will display: Dimensions for an object can't be negative, please insert only positive whole numbers! java.lang.NumberFormatException: For input string: "ciao" Exception message was: 'For input string: "ciao"' – user3353167 Feb 25 '14 at 21:24
  • that is because you are catching NumberFormatException in your outer try/catch block and throwing a new exception with a different message. – jgitter Feb 25 '14 at 21:26
  • so I shouldn't use the NumberFormatException? or how can I check if the input is not a number and eventually throw the exception? – user3353167 Feb 25 '14 at 21:32
  • My point is you don't have to. Java will throw it for you, just stop catching it in your outer block. – jgitter Feb 25 '14 at 21:35
  • Also, my comment above is incorrect, you aren't throwing a new exception, you're just catching the existing one. You should add a throw exception; line at the end of the block or remove the catch altogether. – jgitter Feb 25 '14 at 21:38
  • i understand I don't have to, I get what you mean now. But It would be also useful to learn how to get the input and use it, could you please help me? – user3353167 Feb 25 '14 at 21:40
  • thank you :) my question is: when i type something in the input, I'd like to store that "something", and use it for something else. In this case to throw a new exception, but might be useful for many other things. – user3353167 Feb 25 '14 at 21:47
  • You're already doing that with: int width = Integer.parseInt(args[0]); If you want to store it as a string do this: String width = args[0]; I guess I'm still not sure what you're asking. – jgitter Feb 25 '14 at 22:00
  • I'll try to explain better, sorry for my bad explanation: I will type hello into the console. It will store hello into my ineger.parseInt. So if I wanted to throw a new custom exception, recalling that input, which says:"that's not a number, but a string", how should I do it? – user3353167 Feb 25 '14 at 22:04
  • You can't store a string in an integer variable. You can store it as a String as I mentioned, or just refer back to the initial args array. I'll try to code up a quick example in my answer. – jgitter Feb 25 '14 at 22:11
  • so if I wanted to type for instance 1 -2 3, my output should be: "Dimensions for a cube can't be negative, please insert only positive whole numbers! Exception message was: 'The argument -2 is not a valid number!'java.lang.NumberFormatException: The argument -2 is not a valid number! " and I'd like to throw an exception which will do the same if I typed 1 hello 3. so it should go: "The input is not a valid number, please enter a positive whole number Exception message was: 'The argument is not a valid number!'java.lang.NumberFormatException: The argument hello is not a valid number! ". – user3353167 Feb 25 '14 at 23:03
  • I was actually thinking (hopefully is not too wrong) to put an if else statement inside the catch, where if the input entered is not a number, then it will throw an exception saying that is a string and not a number, else if is a negative number will throw an exception saying that i a negative number. Is it possible? and if yes, how can I do that? – user3353167 Feb 25 '14 at 23:46
  • I don't want to preach java standards at you too much here, but the NumberFormatException already tells you exactly that. If you *really* feel like you need more than that, you can catch the exception, log an error message, and then rethrow the exception so it bubbles out. – jgitter Feb 26 '14 at 16:04
-1

You can create your own exception class and throw the instance of that class from a method.

The exception class:

// Extending Exception makes your class throwable
class MyException extends Exception {

    public MyException( String string ) {
        super( string );
    }
}

And for parsing the input string to integer, call a method like this :

int width = parseInt(args[0]);

where your parseInt() method throws your custom exception as follows:

    private int parseInt( String number ) throws Exception {
        try {
            return Integer.parseInt( number );
        } catch ( Exception e ) {
            throw new MyException( "The input is not a number" );
        }
    }

Now, you can catch your custom exception MyException similar to other standard exceptions:

       // catching your custom exception
       catch ( MyException e ) {
            System.err.println( e );
        }

        // if there's one than more argument error will be displayed
        catch (ArrayIndexOutOfBoundsException exception)
        {
          System.out.println("Please supply width, depth and hight arguments!");
          System.out.println("Exception message was: '" + exception.getMessage() 
                             + "'");
          System.err.println(exception);
        } // catch          

       // if a negative number is entered error will be displayed
       catch (NumberFormatException exception)
       {
         System.out.println("Dimensions for a cube can't be negative, please "
                                   + "insert only positive whole numbers!");
         System.out.println("Exception message was: '" + exception.getMessage() 
                                   + "'");     
         System.err.println(exception);
       } // catch
Manoj Shrestha
  • 4,246
  • 5
  • 47
  • 67
  • -1 Don't catch the general `Exception` class. Also, creating an unique class is redundant as it is doing the same thing as the `NumberFormatException`. Also, I have no idea when you would ever catch a `NumberFormatException` given your code. – MirroredFate Feb 25 '14 at 22:24
  • is it possibile to do it within one class? and if yes, could you show me how please? – user3353167 Feb 25 '14 at 23:02