java - Scanner in loop never stops reading inputs -
my code below supposed prompting user numbers. part works, after user inputs numbers, nothing happens. why code stop after user inputs numbers?
public static void main(string[] args) { arraylist<double> inputs = getnumbers(); int numberofitemstodrop = getlowestnumber(); // ... } public static arraylist<double> getnumbers() { arraylist<double> inputs = new arraylist <double> (); scanner in = new scanner(system.in); system.out.println("please enter 5 ten numbers on 1 line separated spaces."); double vals = in.nextdouble(); while (in.hasnextdouble()) { inputs.add(in.nextdouble()); } return inputs; } public static int getlowestnumber() { int numberofitemstodrop = 0; system.out.println("how many of lowest values should dropped?"); scanner in = new scanner(system.in); numberofitemstodrop = in.nextint(); return numberofitemstodrop; }
you have 2 problems: scanner
, , indistinguishable inputs.
in order appear in code...
1. dueling scanners
as general rule, want 1 scanner
per input stream. if first scanner
"reads ahead" fill input buffer, bytes vanish forever when scanner
gets garbage-collected. typically leads nosuchelementexception
when next scanner
tries read inputs no longer exist.
note not same trying read closed input stream (see "java.util.nosuchelementexception - scanner reading user input") --- losing inputs can happen when input stream still open.
a better strategy create 1 scanner
, , pass each method needs read it:
public static void main(final string[] args) { final scanner in = new scanner(system.in); // 1 , only. arraylist<double> inputs = getnumbers(in); int numbertodrop = getlowestnumber(in); // ... }
2. indistinguishable inputs
also, need way determine end of floating-point data , start of integer. can't hasnextdouble
, because integer input 3
double
. fortunately, have told user read end of line, , nextline
that.
i created throw-away scanner
read double
values string
returned nextline
. (the new scanner parser
not conflict scanner in
, because read different sources.)
public static arraylist<double> getnumbers(final scanner in) { system.out.println( "please enter 5 ten numbers on 1 line " + "separated spaces." ); final string s = in.nextline(); final scanner parser = new scanner(s); arraylist<double> inputs = new arraylist<>(); while (parser.hasnextdouble()) { inputs.add(parser.nextdouble()); } parser.close(); return inputs; }
i checked input hasnextint
, returned 0
if wasn't valid integer:
public static int getlowestnumber(final scanner in) { system.out.println( "how many of lowest values should dropped?" ); if (in.hasnextint()) { return in.nextint(); } return 0; }
i think both of scanning methods should throw exceptions if encounter bogus inputs, rather trying make this... thing worse bogus data plausible result based on bogus data.
Comments
Post a Comment