如何正确显示对象数组中的原始值?

时间:2017-04-03 19:04:20

标签: java arrays object

import java.util.*;
public class Student 
{
static CollegeCourse[] theirCourses = new CollegeCourse[5];

public static void main(String[] args)
{

    int ID;
    Scanner input = new Scanner(System.in);


    /////////////////////////////////////////////////// Assigns student ID
    System.out.println("Please enter your student ID >>");
        ID  = input.nextInt();
    ///////////////////////////////////////////// Wasn't sure how to populate the array
        theirCourses[0] = new CollegeCourse("CIS 110", 3, 'A'); 
        theirCourses[1] = new CollegeCourse("MATH 330", 2, 'A');
        theirCourses[2] = new CollegeCourse("FR ENG 110", 2, 'A');
        theirCourses[3] = new CollegeCourse("PHYSICS 110", 1, 'B');
        theirCourses[4] = new CollegeCourse("GAMING 110", 1, 'C');


    theirCourses[0].setCID("CIS 110");
    theirCourses[1].setCID("MATH 330");
    theirCourses[2].setCID("FR ENG 110");
    theirCourses[3].setCID("PHYSICS 110");
    theirCourses[4].setCID("GAMING 110");

    theirCourses[0].setHours(3);
    theirCourses[1].setHours(2);
    theirCourses[2].setHours(2);
    theirCourses[3].setHours(1);
    theirCourses[4].setHours(1);

    theirCourses[0].setGrade('A');
    theirCourses[1].setGrade('A');
    theirCourses[2].setGrade('A');
    theirCourses[3].setGrade('B');
    theirCourses[4].setGrade('C');

////////////////////////////////////////////////////////////////// Displays all preset populated courses
        System.out.println("Please enter a number for the course you would to view, 0-4.\n" 
                + "Courses are:");
for(int x = 0; x < theirCourses.length; ++ x)
     {
        System.out.println(theirCourses[x].getCID());

     }
}
}

如果我没有填充下面数组的重复语句,我已经在一行中为其分配了一个字符串,一个字符串,一个字符串,一个字符串和一个字符串,那么当我到达底部我有print语句时:的System.out.println(theirCourses [X] .getCID());我一直得到一个空输出。关于可能是什么原因的任何线索?我也会发布客户端类。

public class CollegeCourse 
{
private String cID;
private int cHours;
private char grade;

public CollegeCourse(String string, int i, char c) 
{

}

public void setCID(String c)
{
    cID = c;
}

public String getCID()
{
    return cID;
}

public void setHours(int h)
{
    cHours = h;
}

public int getHours()
{
    return cHours;
}

public void setGrade(char g)
{
    grade = g;
}

public char getGrade()
{
    return grade;
}


}

1 个答案:

答案 0 :(得分:0)

就像@JB Nizet提到的那样,你的构造函数没有做任何事情。构造函数正在获取参数,将它们设置为值。

public CollegeCourse(String string, int i, char c) {
    cID = string;
    cHours = i;
    grade = c;
}

摆脱所有setCID,setHours和setGrade。这是15行不必要的代码。