4 Replies - 552 Views - Last Post: 30 November 2010 - 11:29 PM Rate Topic: -----

#1 turbox  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 30-November 10

Adding Objects to an array

Posted 30 November 2010 - 10:29 PM

Ok, so i have to write a class where I can create list of students and add them to an array. I was wondering if i could make an array of objects and just add the students to that array or am i going to have to create another class? Thanks in advance.
class Student{
	public byte count = 0;
	public String id;
	public String name;
	public String score = " ";
	public char sex;
	public int age;
	public int labs[] = new int [12];
	
	public Student(){
			}
	
	public void setName(String newName){
		name = newName;
	}
	
	public void setSex(char newSex){
		sex = newSex;
	}
	
	public void setAge(int newAge){
		if(newAge < 100 && newAge > 0)
			age = newAge;
		else
			System.out.println("Invalid Age");
	}
	
	public void setId(String newId){
		if(newId.length() != 9)
			System.out.println("Invalid ID. Must be 9 digits long");
		else
			id = newId;
	}

	public void setScore(byte labNum, byte score){
		labs[labNum] = score;
		}	
	
		
}//end of student class
	



Is This A Good Question/Topic? 0
  • +

Replies To: Adding Objects to an array

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,392
  • Joined: 27-December 08

Re: Adding Objects to an array

Posted 30 November 2010 - 11:09 PM

Best practice would be to design a class, like a School class, to encapsulate a Student[].
Was This Post Helpful? 0
  • +
  • -

#3 turbox  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 30-November 10

Re: Adding Objects to an array

Posted 30 November 2010 - 11:15 PM

Ok, but how will i able to make a student and set the students id and lab scores if I made a School class?
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,392
  • Joined: 27-December 08

Re: Adding Objects to an array

Posted 30 November 2010 - 11:21 PM

A small example below:
//create your array, which stores numStudentsYouWant
//null variables
Student[] s = new Studen[numStudentsYouWant];

//instantiate a new Student
s[0] = new Student();

//and set it's name to 0
s[0].setName("Name");



I cover a basic inventory management system in my tutorial Moving Away From Parallel Arrays using a similar setup as yours. You might want to check out my tutorial.
Was This Post Helpful? 1
  • +
  • -

#5 turbox  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 30-November 10

Re: Adding Objects to an array

Posted 30 November 2010 - 11:29 PM

Ok, thanks for your help and I will definitely check out your tutorial.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1