初始化对象数组并传递值

发布于 2024-12-12 21:32:19 字数 395 浏览 5 评论 0原文

我知道论坛里有很多这样的问题,但搜索了好一阵子还没有找到答案。我对编程也很陌生,所以请不要攻击我。

我想在我的类中创建 8 个对象并向它们传递不同的值。

fe

public class exampleClass(){
int value;
}

然后初始化它们:

for(int i=0; i<7; i++){
exampleClass c= new  // I get lost at this point
                    //and how can we pass "i" to the var "value" inside the new objects?
}

非常感谢!

I know there are plenty of question like this in the forum, but after searching for a good while I havent found the answer. I'm also very new to programming so dont flame me please.

I want to creat 8 objects off my class and pass different values to them.

f.e.

public class exampleClass(){
int value;
}

and then init them:

for(int i=0; i<7; i++){
exampleClass c= new  // I get lost at this point
                    //and how can we pass "i" to the var "value" inside the new objects?
}

thanks a lot!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

魔法少女 2024-12-19 21:32:19

您需要为 ExampleClass 提供一个构造函数来填充该值。例如:

public class ExampleClass {
    private final int counter;

    public ExampleClass(int counter) {
        this.counter = counter;
    }
}

...

ExampleClass[] array = new ExampleClass[7];
for (int i = 0; i < array.length; i++) {
    array[i] = new ExampleClass(i);
}

You need to give ExampleClass a constructor to populate the value. For example:

public class ExampleClass {
    private final int counter;

    public ExampleClass(int counter) {
        this.counter = counter;
    }
}

...

ExampleClass[] array = new ExampleClass[7];
for (int i = 0; i < array.length; i++) {
    array[i] = new ExampleClass(i);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文