【发布时间】:2021-07-01 10:54:01
【问题描述】:
我很难将两个变量的输入传递到一个数组中,并在引用类的构造函数中传递该数组的值。如有必要,我可以提供更多代码。非常感谢您的帮助!
目前,这是我所在的位置:
System.out.print("No. of subjects to enroll: ");
choice = keyboard.nextInt();
System.out.println("-------------------------------");
String code;
int grade;
String[] codeArray = new String[choice];
int[] gradeArray = new int[choice];
for (int x = 0; x < codeArray.length; x++) {
System.out.print("Code of the subject " + (x + 1) + ": ");
code = keyboard.next();
System.out.println("What's the grade for " + code + ": ");
grade = keyboard.nextInt();
codeArray[x] = code;
gradeArray[x] = grade;
int s = 0;
while (s < codeArray.length) {
// StudentGrades is the constructor where I am passing the input.
sg = new StudentGrades(codeArray[s], gradeArray[s]);
s++;
}
}
这是我通过 getter 方法获取传递的输入的部分。
int i = 0;
System.out.printf("%-5s %15s %n", "Course Code: ", "Grades: ");
while (i < codeArray.length) {
System.out.printf("%-5s %20s %n", sg.getCourseCode(), sg.getGrade());
i++;
}
这是 StudentGrades() 参考类的构造函数:
public StudentGrades(String courseCode, int grade) {
this.courseCode = courseCode;
this.grade = grade;
}
这是我得到的示例输出。如您所见,它只打印 it412 主题代码。我尝试使用参数 0 代替 S,但它也只显示 it411。
No. of subjects to enroll: 2
-------------------------------
Code of the subject 1: it411
What's the grade for it411: 90
Code of the subject 2: it412
What's the grade for it412: 91
Course Code: Grades:
it412 91
it412 91
-------------------------------
【问题讨论】:
-
看起来
sg在每次迭代时都会重新分配,因此在循环之后sg将包含最后分配的值。然后下一个循环再次迭代,显示sg。 -
@AndrewS 我尝试将 sg 放在循环之外,但它仍然显示相同的输出。
-
只有一个
sg,所以在第一个循环结束后它总是相同的值。尝试将System.out.printf移动到另一个循环。
标签: java arrays class reference