How to get Java to wait for user Input -
i trying make irc bot channel. bot able take commands console. in attempt make main loop wait user input added loop:
while(!userinput.hasnext());
this did not seem work. have heard of bufferedreader have never used , not sure if able solve problem.
while(true) { system.out.println("ready new command sir."); scanner userinput = new scanner(system.in); while(!userinput.hasnext()); string input = ""; if (userinput.hasnext()) input = userinput.nextline(); system.out.println("input '" + input + "'"); if (!input.equals("")) { //main code } userinput.close(); thread.sleep(1000); }
there no need check available input waiting , sleeping until there since scanner.nextline()
block until line available.
have @ example wrote demonstrate it:
public class scannertest { public static void main(string[] args) { scanner scanner = new scanner(system.in); try { while (true) { system.out.println("please input line"); long = system.currenttimemillis(); string line = scanner.nextline(); long = system.currenttimemillis(); system.out.printf("waited %.3fs user input%n", (now - then) / 1000d); system.out.printf("user input was: %s%n", line); } } catch(illegalstateexception | nosuchelementexception e) { // system.in has been closed system.out.println("system.in closed; exiting"); } } }
please input line
hello
waited 1.892s user input
user input was: hello
please input line
^d
system.in closed; exiting
so have use scanner.nextline()
, app wait until user has entered newline. don't want define scanner inside loop , close since you're going use again in next iteration:
scanner userinput = new scanner(system.in); while(true) { system.out.println("ready new command sir."); string input = userinput.nextline(); system.out.println("input '" + input + "'"); if (!input.isempty()) { // handle input } } }
Comments
Post a Comment