Hello all, I just learning java and I'm having a hell of a time figuring objects and classes, constructors, static and non-static, etc. Anyway, I have a simple problem that I can't figure out. The output from the program below
is:
Name0 null Units 0 Grade A
Grade Points 4
Name0 null Units 0 Grade B
Grade Points 3
Name0 null Units 0 Grade C
Grade Points 2
Question is, why are the Names null and the Units 0, but the Grade and Grade Points displays the correct info?
is:
Name0 null Units 0 Grade A
Grade Points 4
Name0 null Units 0 Grade B
Grade Points 3
Name0 null Units 0 Grade C
Grade Points 2
Question is, why are the Names null and the Units 0, but the Grade and Grade Points displays the correct info?
Code:
import java.util.*;
public class temp
{
public static void main (String[] arg)
{
Student[] studentList = new Student[3];
studentList[0] = new Student("Name0");
studentList[1] = new Student("Name1");
studentList[2] = new Student("Name2");
studentList[0] = new Student(4);
studentList[1] = new Student(4);
studentList[2] = new Student(3);
studentList[0] = new Student('A');
studentList[1] = new Student('B');
studentList[2] = new Student('C');
for (Student e : studentList)
{
System.out.println("Name0 " + e.getName() + " Units " + e.getUnits() + " Grade " + e.getGrade());
System.out.println("Grade points " + e.getGradePoints());
}
}// main
}
class Student
{
//constructor
public Student (String n)
{
name = n;
}
public Student(int u)
{
units = u;
}
public Student(char g)
{
grade = g;
}
//methods
public String getName()
{
return name;
}
public int getUnits()
{
return units;
}
public char getGrade()
{
return grade;
}
public int getGradePoints()
{
value = 0;
if (grade == 'A')
value = 4;
else if (grade == 'B')
value = 3;
else if (grade == 'C')
value = 2;
else if (grade == 'D')
value = 1;
else if (grade == 'F')
value = 0;
return value;
}
String name;
int units;
char grade;
int value;
}
Last edited by a moderator: