【发布时间】:2017-03-29 02:36:22
【问题描述】:
我正在编写一个程序,该程序几乎采用一串数字和运算符,将它们拆分,然后对其进行计算。对于 For 循环中的每个运算符,我有四个单独的 IF 语句。代码可以编译,但在第 70 行和第 28 行给了我一个 IndexOutOfBoundsException Index:0 Size:0。有人对为什么会发生这种情况有任何建议吗?谢谢。
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);
}
} //
【问题讨论】:
-
第 70 行和第 28 行分别是哪几行?请不要让我们为自己着想......顺便说一句,我已经从你的问题中删除了“JavaScript”标签,因为 JavaScript 和 Java 是完全不同的语言。
-
return andList.get(0);此列表为空 -
好吧,当我编译它并手动提供
expr与您的示例值时,我得到以下输出(没有抛出异常): expr: 4+5-12/3.5-5.4*3.14 Operators:[ +, -, /, -, *] 操作数:[4, 5, 12, 3.5, 5.4, 3.14] 表达式:4+5-12/3.5-5.4*3.14 计算结果为 -0.2333333333333334 进程以退出代码 0 -
每个
if块之后的四行应该是inside 那些if块,不是吗?它们是缩进的,好像你认为它们属于ifs,但它们在每个块的结束}之后。目前,每个if块内部的唯一内容是对永远不会读取的变量的赋值。
标签: java if-statement arraylist indexoutofboundsexception