I am writing a program that pretty much is taking a string of numbers and operators, splitting them up, then doing the calculations on it. I have four separate IF statements for each operator inside a For loop. The code compiles, but gives me an IndexOutOfBoundsException Index:0 Size:0 at lines 70 and 28. Does anyone have any suggestions as to why this is happening? Thanks.
import java.util.*;
import java.io.*;
public class Lab8
{
public static void main( String[] args)
{
if ( args.length<1) { System.out.println("FATAL ERROR: Missing expression on command line\nexample: java Lab8 3+13/5-16*3\n"); System.exit(0); }
String expr= args[0]; // i.e. somethinig like "4+5-12/3.5-5.4*3.14";
System.out.println( "expr: " + expr );
ArrayList<String> operatorList = new ArrayList<String>();
ArrayList<String> operandList = new ArrayList<String>();
StringTokenizer st = new StringTokenizer( expr,"+-*/", true );
while (st.hasMoreTokens())
{
String token = st.nextToken();
if ("+-/*".contains(token))
operatorList.add(token);
else
operandList.add(token);
}
System.out.println("Operators:" + operatorList);
System.out.println("Operands:" + operandList);
double result = evaluate( operatorList, operandList );
System.out.println("The expression: " + expr + " evalutes to " + result + "\n");
} // END MAIN
static double evaluate( ArrayList<String> operatorList, ArrayList<String> operandList)
{
String operator;
double result;
ArrayList<Double> andList = new ArrayList<Double>();
for( String op : operandList )
{
andList.add( Double.parseDouble(op) );
}
for(int i=0;i<operatorList.size();++i)
{
if(operatorList.get(i).equals("*"))
{
operator = operatorList.get(i);
}
result = andList.get(i) * andList.get(i+1);
andList.set(i,result);
//operandList.set(i,result);
andList.remove(i+1);
operatorList.remove(i);
if(operatorList.get(i).equals("/"))
{
operator = operatorList.get(i);
}
result = andList.get(i) / andList.get(i+1);
andList.set(i,result);
andList.remove(i+1);
operatorList.remove(i);
if(operatorList.get(i).equals("+"))
{
operator = operatorList.get(i);
}
result = andList.get(i) + andList.get(i+1);
andList.set(i,result);
andList.remove(i+1);
operatorList.remove(i);
if(operatorList.get(i).equals("-"))
{
operator = operatorList.get(i);
}
result = andList.get(i) - andList.get(i+1);
andList.set(i,result);
andList.remove(i+1);
operatorList.remove(i);
}
return andList.get(0);
}
} //
Aucun commentaire:
Enregistrer un commentaire