Java对象数组可以将元素初始化为非null值吗? [英] Can Java object arrays initialize elements as non-null values?

查看:70
本文介绍了Java对象数组可以将元素初始化为非null值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java领域还很陌生,我很难解决如何解决这个困扰我的空指针异常.

I'm pretty new at Java and I'm having a tough time figuring out how to fix this null pointer exception that has been troubling me.

我知道问题出在哪里,我知道什么是空指针异常,但是我不知道如何使程序正常工作.

I know where the problem occurs and I know what a null pointer exception is, but I have no idea how I'm going to make my program work.

以下是发生问题的代码段:

Here's the code snippet where the problem is occuring:

public static void main(String[] args) {
 Scanner input = new Scanner(System.in);

    Account[] atm = new Account[10];

    for (int i = 0; i < 10; i++){
        atm[i].setId(i);
        atm[i].setBalance(100.00);
    }

就像我说的那样,我知道发生这种情况是因为atm []中的对象为空,但是我不确定如何解决该问题.

Like I said, I know that it happens because the objects in atm[] are null, but I'm not sure how to fix the problem.

我确定这是一个愚蠢的错误,因为这些都是我经常犯的错误,但是你们能提供的任何帮助都会使我过得开心.

I'm sure it's some silly mistake because those are the kinds of mistakes I make on a regular basis, but any help that you guys can give would make my day.

谢谢!

推荐答案

您的整个数组为空!请记住,数组永远不会在Java中自动初始化,除非它们是整数,浮点数,双精度数或布尔值的数组.

Your entire array is null ! remember , arrays are never automatically initialized in java, unless they are arrays of ints,floats,doubles, or booleans.

Scanner input = new Scanner//System.in.Scanner;

Account[] atm = new Account[10];

for (int i = 0; i < 10; i++){
    **atm[i] = new Account();**
    atm[i].setId(i);
    atm[i].setBalance(100.00);
}

当您声明包含对象的数组时,将其读为:我正在创建将包含'x'个对象的数组."(正确),然后继续实例化那些对象

When you're declaring arrays that hold objects, read it as, "I'm creating an array that will hold 'x' objects." (correct), and then proceed to instantiate those objects

...相对于...

...as opposed to...

我正在创建一个包含'x'个对象的数组."(不正确),因为其中还没有创建任何对象,因为其中尚未创建.

"I'm creating an array with 'x' objects in it." (incorrect) since there aren't any objects in there yet because they haven't been created.

这篇关于Java对象数组可以将元素初始化为非null值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆