Java OOP-Accessing the last element in an array of objects -
i practicing object orientation here entering in basketball player names , how many points scored , rebounds grabbed.
how go through each element in array of objects find last player amount of points?
this code have far enter information. need in second forloop examine each element , display last element fits criteria?
class basketballobj { public static void main (string[]args) { basketball bbarray[]; string thename; int thepoints; int therebounds; int index; int noofelements = 0; bbarray = new basketball[3]; for(index = 0; index < bbarray.length; index++) { system.out.println("enter name "); thename = easyin.getstring(); system.out.println("enter points scored "); thepoints = easyin.getint(); system.out.println("enter rebounds grabbed "); therebounds = easyin.getint(); bbarray[index] = new basketball(thename, thepoints, therebounds); noofelements++; } for(index = 0; index < bbarray.length; index++) { if(bbarray[index].getpoints() % 2 == 0) { } } } }
well if want find last player amount of points, don't want go through each element ;-). try:
for(index = bbarray.length-1; index >= 0; index--) { if(bbarray[index].getpoints() % 2 == 0) { //add whatever relevant code here. break; //this line breaks loop (because you've found player amount of score } }
we start @ bbarray.length-1
because while array contains 3 elements, arrays zero-indexed. meaning first element, have call bbarray[0]
. call bbarray[2]
last element.
Comments
Post a Comment