java - searching by last name in an array -
i made contact list 3 classes, contactlist class holds array stores last name, first name, street, city, state, zip, country, email, phone no., , notes.
i want implement search function last name class of contactlist, shows information of contact has last name user searched for, cant seem work. :(
import java.util.*; public class contactlist { //declaration of array , attributes private final int size = 10; private person [ ] list; private int nextemptyelementinarray = 0; // constructor contactlist object public contactlist () { list = new person [size]; } // method adds new contact array public void addnewcontact() { list[nextemptyelementinarray] = new person(); list[nextemptyelementinarray].read(); nextemptyelementinarray++; } // method retrieves contacts last name int searchbylastname(person [] list) { scanner console; console = new scanner(system.in); string searchbylastname = console.next(); (int i= 0; i< list.length; i++) { if (list[nextemptyelementinarray].lastname.equals(searchbylastname)) return i; } return -1; } }
your list
subscript appears wrong: each iteration of loop you're doing this:
if (list[nextemptyelementinarray].lastname.equals(searchbylastname))
if understand question correctly, should doing this:
if (list[i].lastname.equals(searchbylastname))
also, careful naming variable same function. @ best it'll cause confusion.
[edit] noticed you're pre-allocating list, managing actual content length using nextemptyelementinarray
. for
loop should go this:
for (int i= 0; i< nextemptyelementinarray; i++)
Comments
Post a Comment