gpt4 book ai didi

java - 如何初始化数组的元素(1 到 10),然后在打印元素的方法中使用该构造函数?

转载 作者:行者123 更新时间:2023-12-02 10:22:38 25 4
gpt4 key购买 nike

我有一个面向对象编程课的作业。我一直在尝试获取在构造函数中初始化的数组的值,并使用该构造函数中的值以名为 printArrayValues 的不同方法打印它们。 。我似乎无法“调用”或返回方法中的值。我已经排查了几个小时,但我感到很沮丧。

作业步骤如下:

  • ExerciseOne 的构造函数类初始化并实例化myArray作为十个整数的数组,并用值 1 初始化数组的元素通过10 ,使用 for 循环。
    • 您必须根据 for 循环索引变量分配值,例如 i
  • 该类有一个名为 printArrayValues 的方法使用 for 循环和 System.out.print()语句打印出数组元素的值,如示例输出所示。
    • 该方法没有参数,也没有返回值。

我尝试在构造函数中创建一个新变量,然后在方法中调用它,但它不起作用。

public class ExerciseOne {

public int[] myArray;

public static void main(String[] args) {
ExerciseOne aExerciseOne = new ExerciseOne();
aExerciseOne.printArrayValues();

}

ExerciseOne() {
for (int i = 0; i < myArray.length; i++) {
this.myArray = new int[i];
}

}

public void printArrayValues() {
System.out.print("myArray = {");
for (int a = 0; a < myArray.length; a++) {
System.out.print((myArray[a] + 1));
if (a < 9) {
System.out.print(",");
}
else {
System.out.print("};");
}

}

}
//
//public void displayArrayProduct() {
// for (int : myArray) {
//
// }
//
//}

}

我很沮丧,只是在方法中创建了循环来初始化它。这对于作业来说是不正确的,但我想继续。老实说,我现在很迷茫,如果这让帮助我变得更加困难,我很抱歉。

最佳答案

您可以尝试此代码。

public class ExerciseOne {

public int[] myArray = new int[10];

public static void main(String[] args) {
ExerciseOne aExerciseOne = new ExerciseOne();
aExerciseOne.printArrayValues();
}

ExerciseOne() {
for (int i = 0; i < myArray.length; i++) {
this.myArray[i] = i+1;
}
}

public void printArrayValues() {
System.out.print("myArray = {");
for (int a = 0; a < myArray.length; a++) {
System.out.print((myArray[a]));
if (a < 9) {
System.out.print(",");
}
else {
System.out.print("};");
}
}
}
}

输出:myArray = {1,2,3,4,5,6,7,8,9,10};

关于java - 如何初始化数组的元素(1 到 10),然后在打印元素的方法中使用该构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54224142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com