好。所以我正在尝试编写一个应用程序,以正确的操作顺序解决问题(即PEMDAS,但没有PE lol)。我可能做错了,但无论如何。我需要帮助的是,作为迭代遍历数组中的每个元素,如果它是一个运算符,我删除了两个元素(运算符周围的数字,因为我将运算符替换为正确的计算,所以一个包含三个元素的数组,5 +5,将成为一个带有一个元素的数组,10)这很好,但for语句条件不会更新,换句话说,当我更新数组时,array.length会变短,但是for-statement无法识别并继续传递数组的边界,这会导致outofbounds错误。最好的解释方法是我的代码,所以这里是:
for (i = 0; i < splitEquation.length; i++){
if (splitEquation[i].equals("*")){
splitEquation[i] = Double.toString(Double.parseDouble(splitEquation[i - 1]) * Double.parseDouble(splitEquation[i + 1]));
splitEquation = removeIndex(splitEquation, i - 1);
splitEquation = removeIndex(splitEquation, i + 1);
solution += Double.parseDouble(splitEquation[i - 1]);
}
}
removeIndex():
private String[] removeIndex(String [] s, int index){
String [] n = new String[s.length - 1];
System.arraycopy(s, 0, n, 0, index - 1);
System.arraycopy(s, index, n, index - 1, s.length - index);
return n;
}
提前致谢, -Eric
P.S。如果您需要澄清我的代码所做的事情,请告诉我们。)
答案 0 :(得分:0)
使用ArrayList
会让您的生活变得更轻松:
ArrayList<String> splitEquation =
new ArrayList<String>(Arrays.toList("5","*","5"));
for (i = 0; i < splitEquation.size(); i++){
if (splitEquation.get(i).equals("*")) {
splitEquation.set(i,
(Double.toString(Double.parseDouble(splitEquation.get(i - 1)) *
Double.parseDouble(splitEquation.get(i + 1))));
splitEquation.remove(i - 1); // shortens array by 1
splitEquation.remove(i); // this used to be (i + 1)
i--; // move back one (your computed value)
solution += Double.parseDouble(splitEquation.get(i));
}
}
话虽如此......你真的需要修改你的阵列吗?
编辑:问题现在更加明确,数组正在被修改,因为它需要被评估为一系列表达式。他还想添加加法和减法:
递归函数是你的朋友:)
public static double result(ArrayList<String> mySequence, double total, int index)
{
if (index == 0)
total = Double.parseDouble(mySequence.get(index));
if (index == (mySequence.size() - 1))
return total;
else if (mySequence.get(index).equals("*"))
total *= Double.parseDouble(mySequence.get(index + 1));
else if (mySequence.get(index).equals("/"))
total /= Double.parseDouble(mySequence.get(index + 1));
else if (mySequence.get(index).equals("+"))
{
index++;
double start = Double.parseDouble(mySequence.get(index));
total += result(mySequence, start, index);
return total;
}
else if (mySequence.get(index).equals("-"))
{
index++;
double start = Double.parseDouble(mySequence.get(index));
total -= result(mySequence, start, index);
return total;
}
index++;
return result(mySequence, total, index);
}
public static void main(String args[])
{
ArrayList<String> splitEquation =
new ArrayList<String>(
Arrays.asList("5","*","5","/","5","*","4","-","3","*","8"));
double myResult = result(splitEquation, 0, 0);
System.out.println("Answer is: " + myResult);
}
输出:
答案是:-4.0
答案 1 :(得分:0)
为什么在将输入数组用作只读并创建输出ArrayLists(或更好的堆栈)时修改输入数组?
答案 2 :(得分:0)