• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Loop through the list of objects to get attribute.

 
Kris Danielewski
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class Student


and another class with list.


I am trying to loop through the List to find student == my Entered student number.



How can i list through the list??
 
Devaka Cooray
ExamLab Creator
Marshal
Pie
Posts: 4495
267
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, you can use a for-each loop for this purpose like below:



But this is not a good practice, because you can use Map classes instead of those List classes, so you can get the student quickly and in a smart-way without having a loop.

Devaka.
 
Kris Danielewski
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hmm

I have problem , it repeats enterMarkC for every Student in the list, check for student numbber work...
Currently I am trying to set the attribute of Student class (courseworkMark) by user input.
Looking forward for help with it.
 
Kris Danielewski
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Really need help with it , thanks...
 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would guess that what number equals after the statement "number = sc.next()" and what is returned by "if(s.getStudentNo().contains(number))" are not behaving the way you would like them to. Add some print statements to double check your input value and expected results. Also, I would add a break in your loop once you find the correct Student.

If this is for a class and you are allowed to go further I would definately use Devaka's suggestion to use a Map to make this much much easier. Each Student has a unique number... so you could skip the loop and find the correct Student in one statement using a Map.

HTH GL
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kris,

I'll third Brian and Devaka's suggestion to use one of the Map classes instead of a List. Lists are useful when ordering matters, like in a queue. Maps are much better when it comes to searching.

John.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic