0

when I type in 2 command line arguments I get arrayindexoutofBoundsexception :2 I just do not understand why, when i type in 3 command line arguments it works its just 2 command line arguments which give me an array error

    public static void main(String[] args) {

        if(args.length == 1){
            System.out.println(args[0]); 
        }

        if(args.length == 0) {
                        System.out.println("number of arguments invalid"); 
        }

         else{

            try{

              double a = Double.parseDouble(args[0]);
              double b = Double.parseDouble(args[1]);
              double c = Double.parseDouble(args[2]); 

              if(args.length == 3){
                    System.out.println(a*b*c);
                }

               else if(args.length == 2){
                   System.out.println(a*b);
                } 

                else if (args.length > 3){
                    System.out.println("number of arguments invalid");
                }

            }catch(NumberFormatException e){
                System.out.println("invalid operation");
            }

        } 
    }

} 
  • you check the args length up to `2`, but assume there are `3` present. This is your exception, if you just pass two arguments. – SomeJavaGuy Apr 14 '16 at 13:36
  • Change your **second `if`**, `if(args.length == 0) {`, to `else if(args.length == 0) {` and ***think*** about what a *difference* that makes. – Elliott Frisch Apr 14 '16 at 13:36
  • 1
    The explanation is right there in your code. You are trying to read 3 values from your ``args`` array. What do you expect to happen when the array only has 2 values? – f1sh Apr 14 '16 at 13:36
  • Think about it. If the user only gives you 2 arguments, what happens when your program gets to this line: `double c = Double.parseDouble(args[2]);`? – Rabbit Guy Apr 14 '16 at 13:40
  • thanks so much should of thought about it more, but I understand now thanks guys for the help, I appreciate it. – helpmewithjava Apr 14 '16 at 13:51

0 Answers0