繁体   English   中英

将两个变量的输入传递给数组并传递给参考 class 中的构造函数并打印它们

[英]Passing the inputs of two variables to an array and into the constructor in the reference class and printing them

我很难将两个变量的输入传递到一个数组中,并在引用 class 的构造函数中传递数组的值。 如有必要,我可以提供更多代码。 非常感谢您的帮助!

目前,这是我所在的位置:

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() 参考 class 的构造函数:

public StudentGrades(String courseCode, int grade) {
    this.courseCode = courseCode;
    this.grade = grade;
}

这是我得到的示例 output。 如您所见,它只打印 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 
-------------------------------

如果 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);
  ...

暂无
暂无

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

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