【问题标题】:Passing the inputs of two variables to an array and into the constructor in the reference class and printing them将两个变量的输入传递给数组并传递给引用类中的构造函数并打印它们
【发布时间】: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


【解决方案1】:

如果 StudentGrades 代表 1 个 StudentGrade(如果这是您的意图,您应该重命名它),那么您需要在创建学生成绩时保留一份学生成绩列表。

替换此代码:

while (s < codeArray.length ) {
  sg = new StudentGrades(codeArray[s], gradeArray[s]);
  ...

类似的东西:

List<StudentGrades> studentGrades = new ArrayList<>();
while (s < codeArray.length ) {
  sg = new StudentGrades(codeArray[s], gradeArray[s]);
  studentGrades.add(sg);
  ...

【讨论】:

  • 在代码上试过了,它可以工作。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2013-12-09
  • 2016-08-09
  • 1970-01-01
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
  • 2014-12-29
  • 2012-06-22
相关资源
最近更新 更多