// enter harry,sue,mary,bruce should print out bruce,harry,mary,sue //but i'm getting printed out again hasn't been sorted unsure why? //please help
import java.util.scanner; import java.util.arrays; import java.util.arraylist; import java.util.collections; /** * exercise 31 * horizontal name sort * @author (luke dolamore) * @version (5/04/17) */ public class exercise31 { public static void main(string[] args) { scanner kb = new scanner(system.in); system.out.println("input (end #)"); string input = kb.nextline(); while ( ! input.equals("#") ) { processname(input); input = kb.nextline(); } } //main public static void processname (string line) { scanner scn = new scanner(line); arraylist<string> name = new arraylist<string>(); while ( scn.hasnext() ) { line = scn.next(); scn.usedelimiter(","); name.add(line); collections.sort(name); } ( string nam : name ) { system.out.println(nam); } } } // class exercise31
since know names comma seperated in line passed processname should use split method so
public static void processname (string line) { arraylist<string> name = new arraylist<string>(); //splits string around commas string[] inputs = line.split(","); //now take names/values seperated comma , add them list for(int = 0; < inputs.length; i++) { name.add(inputs[i]); } //sort list once collections.sort(name); //output names/values in sorted order ( string nam : name ) { system.out.println(nam); } }
or define delimeter outside while instead of inside
public static void processname (string line) { scanner scn = new scanner(line); scn.usedelimiter(","); //declare here arraylist<string> name = new arraylist<string>(); while ( scn.hasnext() ) { line = scn.next(); name.add(line); } collections.sort(name); ( string nam : name ) { system.out.println(nam); } }
example run 1
input (end #) bruce,harry,mary,sue bruce harry mary sue #
example run 2
input (end #) z,x,y,r,g,q,a,b,c b c g q r x y z
Comments
Post a Comment