java - Program only reads the first line in the file -
i trying read file contains name on line followed numbers on second line. 3rd line name , 4th numbers , on.
i tested on main method. example file contains name "bobby" , telno 123456, when run lookupentry("bobby"), should telno returned me. works if name "bobby" first name on file. if isn't first, program doent seem recognize name , returns me null. been cracking @ , unable see problem. please advice if see any. thanks.
//directoryentry class , contains string name , string telno along set/ methods them. private directoryentry[] thedirectory = new directoryentry[100]; private int size = 0; public void loaddata(string sourcename) { try { scanner in = new scanner(new file(sourcename)); while (in.hasnextline()){ string name = in.nextline(); string telno = in.nextline(); thedirectory[size] = new directoryentry(name, telno); size++; } in.close(); }catch (filenotfoundexception e){ system.out.println("file not found."); } } public string lookupentry(string name) { find(name); if (find(name) >= 0){ return thedirectory[find(name)].getnumber(); } else{ return null; } } public int find(string name){ (int x=0; x < thedirectory.length; x++){ if (thedirectory[x].getname().equals(name)){ return x; } else{ return -1; } } return -1; }
the following file content:
alan a
123456
bobby b
234567
charlie c
456789
daniel d
567891
eric e
787454
in find method, traverse array, use if, else block. basically, if name you're looking isn't @ index 0, code jump else statement , return -1.
edit: wait sorry, don't see using function in main code anyway... still should fix.
edit 2: that's not main method... scratch again...
fixed code:
public int find(string name){ (int x=0; x < thedirectory.length; x++){ if (thedirectory[x].getname() != null && thedirectory[x].getname().equals(name)){ return x; } } return -1; }
Comments
Post a Comment