Iterating and accessing the methods in an ArrayList of Objects

  • (2 Pages)
  • +
  • 1
  • 2

21 Replies - 866 Views - Last Post: 23 October 2012 - 11:35 PM Rate Topic: -----

#1 shyone  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 16-October 12

Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 09:00 PM

In this first block of code I am supposed to add a new method that is a public method and returns a String called getClassStats. This method is supposed to build a string that is the class roster along with the grade for each student so that it print out like:
Class Roster
First Last: 98
First Last: 85

In doing this I am supposed to use an iterator and a while loop to iterate through the ArrayList of students. I can use a for each loop but I DO NOT want to do so as I want to learn how to do it without that method right now. I was doing it like this but I am getting errors:
public class Roster {

	//
	// Data members
	//
	private ArrayList<Student> students;
	
	
	
	
	// 
	// Constructors
	//
	

	/**
	 * Constructor to create a Roster object.
	 * 
	 */
	public Roster() {
	// Instantiate the ArrayList of students
	ArrayList<Student> students= new ArrayList<Student>();
		
	createStudents();
		
	}

	
	//
	// Operations
	//

	
	
	//
	// Helper methods
	//
	
	private void createStudents() {
		// Create students for the ArrayList
		Student aStudent= new Student("Bugs","Bunny",98);
		Student bStudent= new Student("Daffy","Duck",77);
		Student cStudent= new Student("Elmer", "Fudd",85);
		Student dStudent= new Student();
		
		//Add each student to the students ArrayList
		students.add(aStudent);
		students.add(bStudent);
		students.add(cStudent);
		students.add(dStudent);
		
		// Use the mutator methods of the Student class to set the fourth Student
		// to be "Porky", "Pig", 92
		students.get(3).setFirstName("Porky");
		students.get(3).setLastName("Pig");
		students.get(3).setStudGrade(92);
	
		String getClassStats;
		
		Iterator<Student> studentIterator= students.listIterator(); 
		while studentIterator.hasNext();
		{
			Student aStudent= studentIterator.next();
			System.out.println(aStudent.getClassStats());
		}
		



I am then supposed to be able to go into my other class and add a method call to getClassStats and then print out the string that is returned to check it. I have done this but I am getting errors as well:
public class RosterDemo {
	
	/**
	 * Demos the functionality of the Roster class.
	 */
	public void run()
	{
		// Create a Roster
		Roster theRoster = new Roster();
		//Get class statistics
		System.out.println(getClassStats());
		
	}


Not being able to print that line out is really hurting me because I can't see what I have done but every example I come across people are doing everything in one main method and not having to pull from other classes.

Is This A Good Question/Topic? 0
  • +

Replies To: Iterating and accessing the methods in an ArrayList of Objects

#2 shyone  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 16-October 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 09:21 PM

I am getting less errors now if I change the first block of code to this:
public String getClassStats() {
	
	Iterator<Student> studentIterator= students.listIterator(); 
	while (studentIterator.hasNext())
	{
		Student aStudent= studentIterator.next();
		System.out.println(aStudent.getClassStats());
	}
}
	


This is still not right as I am getting errors on 'system.out.println(aStudent.getClassStats());' and the error says 'The method getClassStats() is undefined for the type Student'

I still do not know how to fix the second block of code.... =(
Was This Post Helpful? 0
  • +
  • -

#3 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 314
  • Joined: 29-September 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 09:44 PM

Well, I dont see the getClassStats() method anywhere, that why the compiler say t is undefined.
Was This Post Helpful? 0
  • +
  • -

#4 shyone  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 16-October 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 09:51 PM

Is not putting it as
public String getClassStats() {



what I am supposed to do? Am I supposed to add something else to getClassStats?
Was This Post Helpful? 0
  • +
  • -

#5 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 314
  • Joined: 29-September 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:00 PM

View Postshyone, on 23 October 2012 - 09:51 PM, said:

Is not putting it as
public String getClassStats() {



what I am supposed to do? Am I supposed to add something else to getClassStats?


Yes. You suppose to add whatever you need in that method to define it. Let me explain to you this way. A method, such as:
public String getClassStats()
{
}


You have the getClassStats() as the name of your method, inside the "( )" is the parameter you want to parse in. For example, getClassStats(MyClass aClass). Here if you use getClassStats(classA), you call the method by specify the name, and inside the ( ), you contain what you want to know. Here you want to know the stats of class A, that why you put classA in side the ( ). after the name of the class and parameter come the body inside {}, you have to direct what this method does, by putting codes in it, compute or whatever you intent for this method. It doesnt magically compute what you want without your direction.... Just like credit card swipe device or something, it has to has components inside and direction to do stuffs, it cant just have the cover outside, and you swipe the card and your bill is charged.

Try your best buddy, keep reading book and code more and more. One year ago, I was as confused as you are now... and I am taught in English, which isnt my first language... there are concepts and things I just dont get at all and cant do much. Not until I pick up the book, code more and after a while, things begin to make sense. Now it is all about how to solve the problem....

This post has been edited by RozenKristal: 23 October 2012 - 10:03 PM

Was This Post Helpful? 0
  • +
  • -

#6 shyone  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 16-October 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:06 PM

If I do it like this
public String getClassStats() {
		getClassStats(String firstName,String lastName, int studGrade);
	}



I get even more errors.
Basically whenever I put in the get class stats it has to give me the same information that I put in the parameters for Student in my Student class like this:
public Student(String firstName, String lastName, int studGrade) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.studGrade = studGrade;


So yup, I'm still doing it wrong and still stuck....
Was This Post Helpful? 0
  • +
  • -

#7 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 314
  • Joined: 29-September 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:11 PM

okay, so you want to know the infer about firstname, last name, and student grade. Since you created a bunch of objects, namely, aStudent, bStudent, then add into arrayList of students. So, in the getClassStats method, you begin to iterate through the list of array, and print the information of each object, namely, aStudent, bStudent and so on. You can use a while loop for that. Urg... why I doing this.. u doing it right... change the aStudent to StudentIterator as you make above and see... it past midnight for me, I guess the god of sleep is kicking in...

I dont think you need this
Student aStudent= studentIterator.next();


This post has been edited by RozenKristal: 23 October 2012 - 10:19 PM

Was This Post Helpful? 0
  • +
  • -

#8 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:15 PM

Why not learn the for each loop? It is very easy to learn and is designed for collections such as the ArrayList you're using.

for([Data type] [variable holder]: [list]){
//You can then get the values from above by using the variable holder here
}



Simple example:
ArrayList<String> countries = new ArrayList<String>();
	countries.add("Panama");
	countries.add("Uruguay");
	countries.add("Peru");
	countries.add("Argentina");
	countries.add("Chile");
	
	//for each loop
	for(String country:countries){
		System.out.println(country);
	}



What your professor is asking for is for you to just create a String inside that method to make an output like the one you posted by use of appending of String and returning that String, and I believe the bulk of the appending should happen inside that for each loop.
Was This Post Helpful? 1
  • +
  • -

#9 shyone  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 16-October 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:20 PM

What about this getClassStats that he is telling us we must add? How does that fit in with all this iterating? I want to learn the most basic method so that I know how to do that method. Just part of learning. At this point I am ready to throw my hands in the arm because I have been on this step for 2.5 hours already and can't figure out what he means by what I posted in my original question on this topic. I can't tell if what I am doing with iterating is right because I can not call the getClassStats method in the rosterdemo class properly without getting a zillion errors.
Was This Post Helpful? 0
  • +
  • -

#10 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 314
  • Joined: 29-September 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:25 PM

Just hope his professor, unlike mine, saying *YOU MUST USE* iterator to go through the list....

Here, from my professor, hope this help u understand iterator
The following example illustrates how to use a ListIterator:

  LinkedList list = new LinkedList();
  list.add(1); list.add(2); list.add(3);  // list is now [1,2,3]
  ListIterator it = list.listIterator();
  Integer first  = it.next(); // first is 1
  Integer second = it.next(); // second is 2
  it.previous(); // note that a call to next() would now return 2
  it.add(4); // element 4 is inserted immediately before the next element that would be returned by next
  // list is now [1,4,2,3];


And this would explain where listiterator locate and how it move around:
http://docs.oracle.c...stIterator.html

This post has been edited by RozenKristal: 23 October 2012 - 10:27 PM

Was This Post Helpful? 1
  • +
  • -

#11 shyone  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 16-October 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:30 PM

// Use the mutator methods of the Student class to set the fourth Student
		// to be "Porky", "Pig", 92
		students.get(3).setFirstName("Porky");
		students.get(3).setLastName("Pig");
		students.get(3).setStudGrade(92);
	
	
	for (String Student: students) {
		System.out.println(Student);
	}



I added that and then I still am getting errors on it. Error at the 'for' line this time that says 'Type mismatch: cannot convert from element type Student to String'???? :blink:

View PostRozenKristal, on 23 October 2012 - 10:25 PM, said:

Just hope his professor, unlike mine, saying *YOU MUST USE* iterator to go through the list....

Here, from my professor, hope this help u understand iterator
The following example illustrates how to use a ListIterator:

  LinkedList list = new LinkedList();
  list.add(1); list.add(2); list.add(3);  // list is now [1,2,3]
  ListIterator it = list.listIterator();
  Integer first  = it.next(); // first is 1
  Integer second = it.next(); // second is 2
  it.previous(); // note that a call to next() would now return 2
  it.add(4); // element 4 is inserted immediately before the next element that would be returned by next
  // list is now [1,4,2,3];


And this would explain where listiterator locate and how it move around:
http://docs.oracle.c...stIterator.html



Mine DOES SAY I must use an 'Iterator and a While Loop.' He does say we can use the for each, but again, I feel that I need to better understand the while loop first.
Was This Post Helpful? 0
  • +
  • -

#12 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 314
  • Joined: 29-September 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:32 PM

Wait a minute, where is your code for Student class?

This post has been edited by RozenKristal: 23 October 2012 - 10:33 PM

Was This Post Helpful? 0
  • +
  • -

#13 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:36 PM

Here's an example from a parallel dimension:

Say, we have a class of Hero for heroes:
public class Hero {
	private String name;
	private String race;
	
	public Hero(String name, String race){
		this.name = name;
		this.race = race;
	}
	
	public String getName(){
		return name;
	}
	public String getRace(){
		return race;
	}
}




Then, we want to get a list of heroes:
public static void main(String[] args) {
	ArrayList<Hero> heroes = new ArrayList<Hero>();
	Hero godOfWar = new Hero("Kratos","Spartan Mortal");
	Hero halo = new Hero("Master Chief","Spartan Earthling");
	Hero mario = new Hero("Mario","Italian Earthling");
	heroes.add(godOfWar);
	heroes.add(halo);
	heroes.add(mario);
	String listOfHeroes = getHeroes(heroes);
	System.out.println(listOfHeroes);

	
}

public static String getHeroes(ArrayList<Hero> heroes){
	String listOfHeroes ="";
	listOfHeroes = "LIST OF HEROES\n";
	listOfHeroes = listOfHeroes + "Name\t| Race\n";
	for(Hero hero:heroes){
		listOfHeroes = listOfHeroes + hero.getName() +"\t|" + hero.getRace() + "\n";
	}
	return listOfHeroes;
}



We get this:

Quote

LIST OF HEROES
Name | Race
Kratos |Spartan Mortal
Master Chief |Spartan Earthling
Mario |Italian Earthling


Also, you're wrong on your attempt at a for each, why are you printing the Student reference type? ^^
Was This Post Helpful? 2
  • +
  • -

#14 RozenKristal  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 314
  • Joined: 29-September 12

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:38 PM

View PostfromTheSprawl, on 23 October 2012 - 10:36 PM, said:

Here's an example from a parallel dimension:

Say, we have a class of Hero for heroes:
public class Hero {
	private String name;
	private String race;
	
	public Hero(String name, String race){
		this.name = name;
		this.race = race;
	}
	
	public String getName(){
		return name;
	}
	public String getRace(){
		return race;
	}
}




Then, we want to get a list of heroes:
public static void main(String[] args) {
	ArrayList<Hero> heroes = new ArrayList<Hero>();
	Hero godOfWar = new Hero("Kratos","Spartan Mortal");
	Hero halo = new Hero("Master Chief","Spartan Earthling");
	Hero mario = new Hero("Mario","Italian Earthling");
	heroes.add(godOfWar);
	heroes.add(halo);
	heroes.add(mario);
	String listOfHeroes = getHeroes(heroes);
	System.out.println(listOfHeroes);

	
}

public static String getHeroes(ArrayList<Hero> heroes){
	String listOfHeroes ="";
	listOfHeroes = "LIST OF HEROES\n";
	listOfHeroes = listOfHeroes + "Name\t| Race\n";
	for(Hero hero:heroes){
		listOfHeroes = listOfHeroes + hero.getName() +"\t|" + hero.getRace() + "\n";
	}
	return listOfHeroes;
}



We get this:

Quote

LIST OF HEROES
Name | Race
Kratos |Spartan Mortal
Master Chief |Spartan Earthling
Mario |Italian Earthling


Also, you're wrong on your attempt at a for each, why are you printing the Student reference type? ^^


Great example, this solve everything :P I didnt know Mario is a hero... LOL, what about Luigi?

If you still want to use while loop, then:
while(students.hasNext())//so while arraylist still have stuffs
{
   you do the StudentIterator.next(); //this will move the iterator one step, and return the first element.
   now here you print what you just got here, using similar way like Sprawl just showed in his example.

}

This post has been edited by RozenKristal: 23 October 2012 - 10:43 PM

Was This Post Helpful? 1
  • +
  • -

#15 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Re: Iterating and accessing the methods in an ArrayList of Objects

Posted 23 October 2012 - 10:44 PM

An iterator and a while loop goes hand in hand:

	ArrayList<String> foods = new ArrayList<String>();
	foods.add("cake");
	foods.add("ice cream");
	foods.add("chicken");
	foods.add("pasta");
	foods.add("chocolate");
	Iterator<String> i =  foods.iterator();
	System.out.println("FOODS!");
	while(i.hasNext()){
		System.out.println(i.next());
	}



The ArrayList has an Iterator object that has a method called hasNext that returns a boolean variable(true if the ArrayList still has a content, false if not). The while loop will run until the iterator returns false. You can get the current value using the next method.

Output:

Quote

FOODS!
cake
ice cream
chicken
pasta
chocolate

Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2