gpt4 book ai didi

java - 如何修复数组越界异常?

转载 作者:行者123 更新时间:2023-12-02 01:16:18 31 4
gpt4 key购买 nike

我正在尝试从字符串数组中提取系数和指数。例如:“x^2 + 2x + 1”或“x^5”或“x^2 -x + 1”。我在此多项式构造函数中编写的代码适用于大多数情况,但当字符串的长度为 1 时,我收到索引越界错误:“Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: Index 1 out ofbounds for长度 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.length,这会导致空指针异常。请记住在java数组中从0开始并以array.length-1结束,所以你的条件应该是我<数组.长度

关于java - 如何修复数组越界异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58494175/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com