简体   繁体   English

Java检索数组并在for每个循环中打印

[英]Java retrieving array and printing it in a for each loop

I am trying to make a program where it retrieves a set of arrays from a different class 我正在尝试制作一个程序,从不同的类中检索一组数组

int barHeights[] = new int[]
{ 1, 2, 3, 4, 5, 6, 7 };

then calling it in a method and printing it out 然后在方法中调用并打印出来

public void init(int[] barHeights)
{
    Bar[] barArray = new Bar[barHeights.length];
    for (Bar bar : barArray){
        System.out.println(bar);
}

i'm unsure why it is printing out 'null' 7 times in a row in the console. 我不确定为什么它在控制台中连续7次打印“ null”。 Shouldn't it be: 不应该是:

1
2
3
4
5
6
7

In line: 排队:

Bar[] barArray = new Bar[barHeights.length];

You are creating an instance of array of Bar class references instead of int. 您正在创建Bar类引用数组而不是int的实例。
This array is automaticly initialized with null values, and in line: 该数组会自动使用空值初始化,并符合以下条件:

for (Bar bar : barArray){
    System.out.println(bar);

You are interating those null values. 您正在插入这些空值。
If you want to retrive the array, which you passed as an argument to method, you should use: 如果要检索作为参数传递给method的数组,则应使用:

public void init(int[] barHeights) {
    for (int i : barHeights) {
        System.out.println(i);
    }
}

you have created arry Bar but not initialized it, so it is initialized with null. 您已经创建了arry Bar,但尚未对其进行初始化,因此将其初始化为null。

Bar[] barArray = new Bar[barHeights.length];

when you loop through barArray 当您遍历barArray

for (Bar bar : barArray){
    System.out.println(bar);

it will display null. 它将显示为空。

Code should be like this. 代码应该是这样的。

class Bar {
    private int height;

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }
}

Algorithm should be like this 算法应该是这样的

1.create another array type of Bar named barArray. 1.创建另一个名为barArray的Bar的数组类型。

2.loop height array named barHeights 2.循环高度数组命名为barHeights

3.within loop create new object of Bar for each round 3.within循环为每一轮创建Bar的新对象

4.set height for each object 4.设置每个对象的高度

5.add bar object to array 5,将条形对象添加到数组

public void init(int[] barHeights)
{
    Bar[] barArray = new Bar[barHeights.length];
    int index=0;
    for (int height : barHeights){
        Bar bar=new Bar();
        bar.setHeight(height);
        barArray[index]=bar;
        index++;
        System.out.println(bar);
    }
}

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

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