-1

Hi I am trying to get the binary operations, by giving the inputs through command line arguments, and I get the exception as "Exception in thread "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at assignment.CommandLineargs.main(CommandLineargs.java:7)"

Here is my code:

import java.util.Arrays;
public class CommandLineargs {


        public static void main(String[] args) {
            int operand1 = Integer.parseInt(args[0]);
            int operand2 = Integer.parseInt(args[1]);
            char binary_operator = args[2].charAt(0);
            System.out.print(args[0] + args[2] + args[1] + " = ");
            switch(binary_operator) {
                case ('+'):
                    System.out.println(operand1 + operand2); break;
                case ('-'):
                    System.out.println(operand1 - operand2); break;
                case ('*'):
                    System.out.println(operand1 * operand2); break;
                case ('/'):
                    System.out.println(operand1 / operand2); break;
                default:
                    System.out.println("Invalid Operator selected");
            }
        }
    }
gkrls
  • 2,618
  • 2
  • 15
  • 29
  • Can you add a comment indicating the line number where your problem is? – ControlAltDel Sep 23 '14 at 15:24
  • Can you give the entire stack trace and what is the command you are issuing from the prompt to execute ... – StackFlowed Sep 23 '14 at 15:25
  • 1
    Why are you converting the array to a string, only to then split it again to an array? Also be aware that arrays are 0-based. So if you are expecting 3 elements, then use indices 0, 1, 2. – Mark Rotteveel Sep 23 '14 at 15:28

2 Answers2

0

Clearly your array doesn't have enough elements.

strArray = strArray.replace("[", "").replace("]", "").replaceAll("[, ]", "");

This line isn't giving strArray of length 3 or 4

As per the error message mentioned

int operand1 = Integer.parseInt(splits[1]);

This line has been throwing exception indicating that splits[1] doesn't exit and hence splits[2] and splits[3]

Nabin
  • 11,216
  • 8
  • 63
  • 98
0

Your problem is

String[] splits = strArray.split("");

What are you splitting it with ???

I had write a similar program :

public static void main (String[]args) {
    String str = "((1+2)*(3+4))-5";
    if(isValid(str)){
        expandString(str);
    }
}

public static boolean isValid(String s) {
    int totalParenthesis = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '(') {
            totalParenthesis++;
        } else if (s.charAt(i) == ')') {
            totalParenthesis--;
        }
        if (totalParenthesis < 0) {
            return false;
        }
    }
    if (totalParenthesis != 0) {
        return false;
    }
    return true;
}

private static void expandString(String str) {
    System.out.println("Called with : "+str);
    if(!(str.contains("("))){
        evalueMyExpresstion(str);
        return;
    }
    String copyString=str;
    int count=-1,positionOfOpen=0,positionOfClose=0;
    for(Character character : str.toCharArray()) {
        count++;
        if(count==str.toCharArray().length){
            evalueMyExpresstion(str);
            return;
        } else if(character.equals('(')) {
            positionOfOpen=count+1;
        } else if(character.equals(')')) {
            positionOfClose=count;
            copyString = str.substring(0, positionOfOpen - 1) + evalueMyExpresstion(
                        str.substring(positionOfOpen, positionOfClose)) + str.substring(positionOfClose + 1);
            System.out.println("Call again with : "+copyString);
            expandString(copyString);
            return;
        }
    }
}

private static String evalueMyExpresstion(String str) {
    System.out.println("operation : "+str);
    String[] operation;
    int returnVal =0;
    if(str.contains("+")){
        operation = str.split("\\+");
        returnVal=Integer.parseInt(operation[0])+ Integer.parseInt(operation[1]);
        System.out.println("+ val : "+returnVal);
        return Integer.toString(returnVal);
    } else if (str.contains("*")){
        operation = str.split("\\*");
        returnVal=Integer.parseInt(operation[0])* Integer.parseInt(operation[1]);
        System.out.println("* val : "+returnVal);
        return Integer.toString(returnVal);
    } else if (str.contains("-")){
        operation = str.split("\\-");
        returnVal=Integer.parseInt(operation[0])- Integer.parseInt(operation[1]);
        System.out.println("- val : "+returnVal);
        return Integer.toString(returnVal);
    }
    System.out.println(str);
    return Integer.toString(returnVal);
}

Output looks like :

Called with : ((1+2)*(3+4))-5
operation : 1+2
+ val : 3
Call again with : (3*(3+4))-5
Called with : (3*(3+4))-5
operation : 3+4
+ val : 7
Call again with : (3*7)-5
Called with : (3*7)-5
operation : 3*7
* val : 21
Call again with : 21-5
Called with : 21-5
operation : 21-5
- val : 16
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
  • Thanks All, i have updated code now, with position changed,but i still get "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at assignment.CommandLineargs.main(CommandLineargs.java:7) " please guide – manjula reddy Sep 23 '14 at 15:36
  • updated code:public class CommandLineargs { public static void main(String[] args)int operand1 = Integer.parseInt(args[0]);int operand2 = Integer.parseInt(args[1]);char binary_operator = args[2].charAt(0);System.out.print(args[0] + args[2] + args[1] + " = ");switch(binary_operator) { case ('+'): System.out.println(operand1 + operand2); break;case ('-'): System.out.println(operand1 - operand2); break;case ('*'): System.out.println(operand1 * operand2); break;case ('/'):System.out.println(operand1 / operand2); break;default:System.out.println("Invalid Operator selected");}}} – manjula reddy Sep 23 '14 at 15:37
  • You need to see my answer. the first 3 lines will give you why you have the error... – StackFlowed Sep 23 '14 at 15:37
  • You need to see the System.out.println(splits.length); just after you split the string. That value is not 4 ... – StackFlowed Sep 23 '14 at 15:43
  • thanks and what should be done to correct it? – manjula reddy Sep 23 '14 at 16:52
  • You need to split the string with a valid character and not "" ... check my solution ... for a similar issue ... – StackFlowed Sep 23 '14 at 16:59
  • But I dont know the string and operator (as it should be entered by the user),also i dont need to deal with multiple parameters at a time, its like one by one. how to deal the issue in this regard. – manjula reddy Sep 23 '14 at 18:07
  • Again see my code your string should be like String str = "((1+2)*(3+4))-5"; or something of this sort ... just use / modify the code give out by me... which should be like String str = args[0]; – StackFlowed Sep 23 '14 at 18:11
  • If you want more help please edit your question with full code and the way you call / run the program with what arguments. without that i will not respond anymore. – StackFlowed Sep 23 '14 at 18:14