gpt4 book ai didi

java - 字符串的 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 05:15:45 25 4
gpt4 key购买 nike

我对 java 还很陌生,还没有掌握这个 NullPointerException 的东西...&我想我可能在正确初始化变量方面遇到问题。

所以我的类中有这些实例变量:

protected String sequence;
protected ArrayList<Character> set = new ArrayList<Character>();
protected char[] op_1;
protected char[] op_2;
protected char[] ans;

&这是它们在构造函数中初始化的方式:

public Puzzle (String puzzle_equation){
int i = puzzle_equation.indexOf('+');
int j = puzzle_equation.indexOf('=');

String operand_1 = puzzle_equation.substring(0, i-1);
String operand_2 = puzzle_equation.substring(i+1, j-1);
String answer = puzzle_equation.substring(j+1);

op_1= operand_1.toCharArray();
op_2= operand_2.toCharArray();
ans= answer.toCharArray();


//initializing set with all the letters existing in the equation without repetition
for (char c : op_1){
if (! set.contains(c)) {
set.add(c);
}
}

for (char c : op_2){
if (! set.contains(c)) {
set.add(c);
}
}

for (char c : ans){
if (! set.contains(c)) {
set.add(c);
}
}


//sequence= " "; --> at 1st i didn't initialize sequence at all in the cunstructor


}

这是该类的方法:

protected void puzzleSolve(int k, String s, ArrayList<Character> u){


for (Character c:u){

if(k==1){

**if(isAnswer(s+u.get(0)))**

System.out.println(s+u.get(0)+" is the correct sequence."+ '\n');
return;

}

else{
u.remove(c);
**puzzleSolve(k-1, s+c , u);**
u.add(c);
removeLastChar(s);
}

}

}

还有另一种方法,只需使用给定的参数调用上面的方法:

 **puzzleSolve(set.size(), sequence , set);**

&最后一个方法是Answer:

protected boolean isAnswer(String seq){

int[] digitAssign =new int[seq.length()];

for (int z=0; z<digitAssign.length; z++){
digitAssign[z] = z;
}

char[] seqArray = seq.toCharArray();


String op_1_to_digit=null ;
String op_2_to_digit=null ;
String ans_to_digit=null ;

//converts the letters of words to the assigned digits to each letter

**for(int n=0; n<op_1_to_digit.length(); n++)**
for(int f=0; f<seqArray.length ; f++){
if (op_1[n] == seqArray[f])
op_1_to_digit += digitAssign[f];
}


//op_2
for(int n=0; n<op_2_to_digit.length(); n++)
for(int f=0; f<seqArray.length ; f++){
if (op_2[n] == seqArray[f])
op_2_to_digit += digitAssign[f];
}

//ans
for(int n=0; n<ans_to_digit.length(); n++)
for(int f=0; f<seqArray.length ; f++){
if (ans[n] == seqArray[f])
ans_to_digit += digitAssign[f];
}


int x= Integer.parseInt(op_1_to_digit);
int y= Integer.parseInt(op_2_to_digit);
int l= Integer.parseInt(ans_to_digit);

return (x+y==l);

}

我在 ** 指示的行上收到 NullPointerException 错误

请帮我解决这个问题。我真的很困惑。

附注我尝试将序列一次初始化为sequence= null; & 一旦像序列=“”; 还有“op_1_to_digit”等,但后来我得到了另一个 OutOfBoundry 异常!

最佳答案

当你说

String op_1_to_digit = null;

您不能像这样立即调用 op_1_to_digit.length()

for(int n=0; n<op_1_to_digit.length(); n++)

因为 Stringnull

关于java - 字符串的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26963920/

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