How do i fix the array out of bounds exception?(如何修复数组越界异常?)
本文介绍了如何修复数组越界异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试从字符串数组中提取系数和指数。例如:"x^2+2x+1"或"x^5"或"x^2-x+1"。我在这个多项式构造函数中编写的代码适用于大多数情况,但是当字符串的长度为1时,我会得到一个超出界限的索引错误:"EXCEPTION in ThREAD"main"java.lang.ArrayIndexOutOfBibsException:index 1 out out bound for Length 1"。我不确定如何解决这个问题。有人能帮我弄一下这段代码吗?
如果数组的长度为1,我已尝试中断While循环。
public class Polynomial extends PolynomialInterface {
public Polynomial(String s) {
// complete this code
Term newTerm;
DList<Term> dList = new DList<Term>();
int exp = 0;
double coef = 0;
s = s.replaceAll(" ", "");
String[] array = s.split("\+|(?=-)");
for(String i : array){
System.out.println("split: " + i);
}
for (int i = 0; i <= array.length; i++) {
while (array[i].contains("x")) {
exp = 0;
if ((array[i].substring(0, 1).equalsIgnoreCase("x"))) {
coef = 1;
}
if (array[i].substring(0, 1).equals("-") && array[i].substring(1, 2).equalsIgnoreCase("x")) {
coef = -1;
exp = 1;
}
if (array[i].contains("^")) {
int index = array[i].indexOf("^");
String myString = "";
if (index != -1) {
myString = array[i].substring(index + 1, index + 2);
if (!myString.isEmpty()) {
exp = Integer.parseInt(myString);
}
}
}
if (!array[i].contains("^")) {
exp = 1;
}
int end = array[i].indexOf("x");
String subString = "";
if (end != -1) {
subString = array[i].substring(0, end);
if (!subString.isEmpty() && !subString.contains("-")) {
coef = Double.parseDouble(subString);
} else if (!subString.isEmpty() && !subString.equals("-")) {
coef = Double.parseDouble(subString);
}
}
newTerm = new Term(coef, exp);
dList.addLast(newTerm);
if(array.length==1){
break;
}
i++;
}
while (array[i].matches("([-]\d*|\d*)") && (i < array.length)) {
coef = Double.parseDouble(array[i]);
exp = 0;
newTerm = new Term(coef, exp);
dList.addLast(newTerm);
break;
}
}
//super.data = dList;
}
当我调试时,我得到了正确的系数和指数,然后迭代,我得到了一个索引越界错误
推荐答案
for (int i = 0; i <= array.length; i++)
您的for循环转到array.long,这会导致空指针异常。 请记住,在Java数组中,从0开始,以array.length-1结束,因此条件应该是 数组长度
(&L)这篇关于如何修复数组越界异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:如何修复数组越界异常?
基础教程推荐
猜你喜欢
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
