dimanche 29 octobre 2017

calculating values in a string

Hi I am new to java programming,

value in a textbox is 322+1*3-5

HERE'S MY PROGRAM FOR IT.

        String abc = tf1.getText();

        String operands[]=abc.split("[+-/*]");
        String operators[]= abc.split("[0-9]");

        int agregate = Integer.parseInt(operands[0]);
        System.out.println(agregate);

        for(int i=1;i<operands.length;i++)
            {
                if(operators[i].equals("+"))
                    {
                    int c = Integer.parseInt(operands[i]);
                    agregate = agregate+c;
                    }
                else if (operators[i].equals("-"))
                    {
                    int c = Integer.parseInt(operands[i]);
                    agregate = agregate-c;
                    }
                else if (operators[i].equals("*"))
                {
                    int c = Integer.parseInt(operands[i]);
                    agregate = agregate*c;
                    }
                else 
                    {
                    int c = Integer.parseInt(operands[i]);
                    agregate = agregate/c;
                    }

could someone help to correct this program to return right value

Aucun commentaire:

Enregistrer un commentaire