java - 我可以不这样做吗?收到 'exception' 错误

标签 java error-handling

出现以下错误:“线程“main”中出现异常 java.lang.NullPointerException” ”

    // Creates 10 accounts
         Account[] AccArray = new Account[10];
// Data fields
        double atmVal;

// Sets each account's discrete id and initial balance to 100
         for (int i=0;i<10;i++){
            AccArray[i].setId(i); // this line is specified in the error
            AccArray[i].setBalance(100);
         }

这编译得很好,但我得到了一个“异常(exception)”(还不确定那些是什么)。

我根本看不出有什么问题,至少这里没有。如果情况确实如此,我将添加更多代码。

最佳答案

您的数组已初始化为包含 10 个帐户,但它们仍然为空。将循环更改为:

 for (int i=0;i<10;i++){
        ArrArray[i] = new Account(); // whatever constructor parameters are needed
        AccArray[i].setId(i); // this line is specified in the error
        AccArray[i].setBalance(100);
     }

话虽如此,我建议您使用小写名称命名变量(例如 accArray)。

关于java - 我可以不这样做吗?收到 'exception' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050331/

相关文章:

Java MySQL : Insert special charactar into database

java - 当我尝试从文件中拆分行时,我不断收到 IndexOutOfBounds 错误

eclipse - Eclipse Mars Tomcat 8服务器消失了

android - 如何在Firebase中创建新的DatabaseError实例?

javascript - 如何中止或停止JavaScript执行?

java - Java代码中的Activiti工作流调用

java - 每次 git 推送都会删除未跟踪的文件

java - 在 AffineTransform.rotate() 之后检索 BufferedImage 边界的新宽度和高度

c# - Web API通用错误处理

php - 引用 - 这个错误在 PHP 中是什么意思?