Java Scanner - Input space separated doubles when the total number of items is unknown -
i have simple java program i'm running in eclipse. command line i'm passing in list of around 100 space separated doubles however, please assume don't know how many items passed in.
at moment i'm reading in entire line, tokenizing , converting doubles shown below:
scanner sc = new scanner(system.in); arraylist<double> stock = new arraylist<double>(); string s = sc.nextline(); string[] split = s.split("\\s+"); (int i=0; i<split.length; i++) { stock.add(double.parsedouble(split[i])); } so, i'm relatively confident above not best way approach such problem. want more code below, when enter data in console , hit enter, program fails respond, in, it's not recognising input list of doubles.
scanner sc = new scanner(system.in); arraylist<double> stock = new arraylist<double>(); while (sc.hasnextdouble()) { double d = sc.nextdouble(); stock.add(d); } so, @ present first code sample works fine, second fails anything. incidentally, have tried adding sc.nextline(); after sc.nextdouble(); call doesn't make difference.
is there i'm doing wrong here or there better approach should taking.
thank in advance.
it because of while-loop. program wait more input system.in forever, because sc.hasnextdouble() evaluate true every time because input system.in infinite, unlike input file.
to me first solution have seems way go if want doubles in 1 line. can clean little , use for-each instead of regular for-loop.
example:
scanner scanner = new scanner(system.in); arraylist<double> doubles = new arraylist<double>(); string inputline = scanner.nextline(); string[] splittedinputline = inputline.split("\\s+"); for(string doublestring : splittedinputline) { doubles.add(double.parsedouble(doublestring)); }
Comments
Post a Comment