[英]Parsing java list of factors with insertions
疯狂长而又必要简介:现在,我正在编写一个合成除法计算器。 为此,有几个步骤(由计算机来完成)。 我已经完成了第一步
3x^2+2x^1+3x^0
)解析为每个术语的片段(例如3x^2
2x^1
等) 3x^2 + 2x^1 + 0x^1
必须输入3,2,0
)。 另外,如果缺少一定程度,则应在位置添加零。 例如,如果输入为3x^2 + 2x^0
,则必须在中间添加零,因为缺少度为1的项。 输出将是3,0,2
。 我为解决此问题所做的工作:
如果我还没有这么说,那我就是用Java编写的。 (请注意:我正在尝试在此处创建MVC。要查看完整的代码,请转到此处 )
//Cycle through all the degrees
for (int i = this.degree; i>=0; i--){
//We can set a boolean value on
//whether we have found the term in the array with the correct degree
boolean found = false;
// arr is the array with all the terms (2x^2) etc.
for (String each : arr){
//checks if the current term is of the degree we are looking for (i)
if(lookForTheTerm(each,i)){
try{
//Add it to the resulting array list
coefficients.add(getCoeffFromString(arr[i]));
}
catch (Exception e){
}
//We found it
found = true;
//Break out of the loop (if we found it, we don't need to keep looking)
break;
}
}
//If we didn't find it, add a 0 to the array list
if(!found){
coefficients.add((float) 0);
}
}
//Not shown: After iterating, reverse the list to be correct
问题:
如果所有条件都存在,则此代码有效。 含义3x^2+1x^1+0x^0
(存在度2,1和0的项)。
如果它们出现故障,那么它会完全疯狂。
如果一个缺失并且它们是有序的,则将其置零,而忽略前导项。
代码有什么问题? 我几乎肯定这是一个语义错误。 我再次尝试提供MVC。 但是如果还不够的话,可以在这里看到完整的代码。
感谢您对高级的帮助
问题1:订购
您正在从第一个术语解析度,然后使用该度遍历这些术语。 如果您将二度放在首位,那么它只会处理2个学期。
您可以通过按学位先对术语进行排序来解决此问题。
问题2:字词少
这是由程度相关的问题引起的,但更糟的是:
coefficients.add(getCoeffFromString(arr[i]));
}
catch (Exception e){
}
你在吃例外。 如果您有2个术语,但有3个学位,那么在索引i处取消引用列表将抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.