【问题标题】:Can I not do this? Getting an 'exception' error我不能这样做吗?收到“异常”错误
【发布时间】:2014-04-14 00:53:39
【问题描述】:

得到以下错误:“.Exception in thread "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);
         }

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

我完全看不出有什么问题,至少这里没有。如果是这样的话,我会添加更多我的代码。

【问题讨论】:

    标签: java error-handling


    【解决方案1】:

    您的数组已经初始化为包含 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)。

    【讨论】:

      【解决方案2】:

      当您创建一个对象数组时,您得到的只是一个大小正确但充满nulls 的数组。您需要通过说出new Account() 并将其分配给数组来创建每个对象。你甚至可以在同一个循环中完成。

      【讨论】:

        【解决方案3】:

        你需要实例化一个Account,假设你有一个空的构造函数Account你会使用这样的东西——

         for (int i=0;i<10;i++) {
           AccArray[i] = new Account(); // <-- like so.
           AccArray[i].setId(i); // this line is specified in the error
           AccArray[i].setBalance(100);
         }
        

        另外,您应该尝试遵循 Java 命名约定......所以可能更像,

        Account[] accounts = new Account[10];
        
         for (int i=0;i<10;i++) {
           accounts[i] = new Account(); // <-- like so.
           accounts[i].setId(i); // this line is specified in the error
           accounts[i].setBalance(100);
         }
        

        【讨论】:

          【解决方案4】:

          正如其他人所指出的,创建一个新的Account 数组实际上并没有创建任何Accounts;你必须用new自己做。 Java 8 为您提供了一种很好的方法:

          Account[] accounts = new Account[10]; 
          Arrays.setAll(accounts, i -> new Account());
          

          setAll 的第二个参数是一个 lambda 表达式,它采用整数参数 i(被设置元素的索引)并将数组元素设置为 new Account()。该表达式实际上并不使用索引,但如果需要,您可以使用一个确实使用 i 的表达式(或块)。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-08-23
            • 2021-10-08
            • 2019-06-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-03-08
            • 1970-01-01
            相关资源
            最近更新 更多