Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

noel4r

macrumors 6502a
Original poster
Jul 17, 2002
661
0
Los Angeles
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?
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:
Your constructor needs to have three parameters, Name, Units and Grade

Code:
public Students (String n, int u, char g)
{
  name = n;
  unit = u;
  grade = g;
}

Create a new student like this

Code:
studentList[0] = new Student ("Brian", 10, 'A');
studentList[1] = new Student ("noel4r", 8, 'B');
studentList[2] = new Student ("Bush", 0, 'F');

What you are doing now is creating 9 Student objects when you only need to create three.
 
Check out GreenFoot.org

It will quickly and visually teach you the concepts of object oriented design. You'll build a simple wombat 'game' in the process.

I'm in the process of creating a local high school programming app club that will teach the fundamentals of app development, good code design and it all pretty much begins with GreenFoot
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.