简体   繁体   English

将String数组转换为Int数组时发生NullPointerException

[英]NullPointerException at conversion of String array to Int array

I am a beginner in programming and decided to make my own binary to decimal converter program for the fun of it. 我是编程的初学者,因此决定开发自己的二进制到十进制转换器程序,以此为乐。 In my program, I move the String array's content to the Int array. 在我的程序中,我将String数组的内容移动到Int数组。 the problem is that I seem to keep getting a NullPointerException error at the code where I change the String to Int. 问题是我似乎在将String更改为Int的代码中始终收到NullPointerException错误。 I have read the error and tried a lot of different methods to get rid of that error, but nothing helps. 我已经阅读了该错误,并尝试了许多其他方法来消除该错误,但是没有任何帮助。 What could I be doing wrong? 我可能做错了什么?

"Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException"

My code: 我的代码:

int ans = 0;
int multi = 0;
strArray = null;
intArray = null;
if (rbBin.isSelected()) {
    txaNew.setText("");
    String num = ftxfOld.getText();
    strArray = num.replaceAll("\\[", "").replaceAll("\\]", "").split(",");

    for (int i = 0; i < strArray.length; i++) {
        try {
            intArray[i] = Integer.parseInt(strArray[i]); //I GET THE ERROR HERE
        } catch (NumberFormatException nfe) {
        }
    }
    for (int j = 0; j < num.length() + 1; j++) {
        multi = intArray[j] * 2 ^ j;
        ans = ans + multi;
    }
}
txaNew.append(Integer.toString(ans));

This happens because in java you have to initialize a variabile before using it. 发生这种情况是因为在Java中,必须在使用可变变量之前对其进行初始化。 In your case when you do it: 就您而言,当您这样做时:

intArray[i] = Integer.parseInt(strArray[i]); //I GET THE ERROR HERE

the initArray is null. initArray为null。

Change your code: 更改您的代码:

strArray = num.replaceAll("\\[", "").replaceAll("\\]", "").split(",");

if (strArray != null){
   //You have to initialize your variable
   intArray = new int[strArray.length];

   for (int i = 0; i < strArray.length; i++) {
     try {
        intArray[i] = Integer.parseInt(strArray[i]);
     } catch (NumberFormatException nfe) {
          nfe.printStackTrace();
     }; 
   }
}

You have to instantiate intArray first. 您必须首先实例化intArray。

intArray = new int[strArray.length];

So you will have: 因此,您将拥有:

String num = ftxfOld.getText();
strArray = num.replaceAll("\\[", "").replaceAll("\\]", "").split(",");
intArray = new int[strArray.length];

for (int i = 0; i < strArray.length; i++) {
try {
  intArray[i] = Integer.parseInt(strArray[i]); //I GET THE ERROR HERE
 } catch (NumberFormatException nfe) {}; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM