Java Converting do-while loop with while loop -
i implementing simple sorting class, , wondering how implement using while loop rather do-while loop.
the outer loop executed once each item in ‘names’ list. however, it’s do-while loop, executed @ least once. lead incorrect result if ‘names’ empty list. should replaced while loop.
sort class
public class sort { public static arraylist<name> sort1(arraylist<name> names) { arraylist<name> results; results = new arraylist<name>(); int count = names.size(); { name firstname = new name("zzz", "zzz"); (name name : names) { if (name.getfirstname().compareto(firstname.getfirstname()) < 0 || name.getfirstname().equals(firstname.getfirstname()) && name.getsurname().compareto(firstname.getsurname()) < 0) { firstname = new name(name.getfirstname(), name.getsurname()); } } results.add(firstname); names.remove(firstname); count--; } while (count > 0); return results; }}}
name class
class name { string firstname; string surname; public name() { } public name(string firstname, string surname) { this.firstname = firstname; this.surname = surname; } public string getfirstname() { return firstname; } public void setfirstname(string firstname) { this.firstname = firstname; } public string getsurname() { return surname; } public void setsurname(string surname) { this.surname = surname; } public string tostring() { return firstname + " " + surname; } public boolean equals(object other) { string fname = ((name) other).firstname; string sname = ((name) other).surname; if (firstname.equals(fname) && surname.equals(sname)) { return true; } else { return false; } }
public class sort { private static void doiterate(list<name> names, list<name> results) { name firstname = new name("zzz", "zzz"); (name name : names) { if (name.getfirstname().compareto(firstname.getfirstname()) < 0 || name.getfirstname().equals(firstname.getfirstname()) && name.getsurname().compareto(firstname.getsurname()) < 0) { firstname = new name(name.getfirstname(), name.getsurname()); } } results.add(firstname); names.remove(firstname); } public static arraylist<name> sort1(arraylist<name> names) { arraylist<name> results; results = new arraylist<name>(); int count = names.size(); doiterate(names, results); count--; while (count > 0) { doiterate(names, results); count--; } return results; }}}
Comments
Post a Comment