An infinite loop while using Scanner - java -
i want ask user whether wants create file named file.elt
or not. i'm trying switch statement using scanner
class.
here code:
system.out.println("do want create file.elt? (y/n)"); stroption=sc.nextline(); outer: while (sc.hasnext()) { switch (stroption) { case "y": case "y": elements.createelements(file); break outer; case "n": case "n": system.out.println("there no file.elt created! ."); break outer; default: system.out.println("please, type y or n."); stroption=sc.nextline(); break; } } sc.close();
the sc
object declared @ beginning of program, ask name of file.
the sc
declaration is:
string file; scanner sc = new scanner(system.in); system.out.println("type name of file .dat ."); file=sc.nextline();
the problem while loop infinite , don't know why.
you not updating stroption
. should move stroption=sc.nextline();
inside while
loop also, thelostmind pointed out, replace hasnext
hasnextline
.
edit
you might consider switch console
. also, may create confirm
utility method since it's common task:
private console console; ... console = system.console(); ... if (confirm("do want create file.elt? (y/n)")) { elements.createelements(file); } else { system.out.println("there no file.elt created! ."); } ... private boolean confirm(string message) { string answer = console.readline(message); while (!answer.matches("[yynn]")) { answer = console.readline("please, type y or n."); } return "y".equalsignorecase(answer); }
note: doesn't work in eclipse.
Comments
Post a Comment