i working on lab 1 of classes therefore looking more explanation actual code.
for part of assignment need read in numbers user until control-d pressed. have while loop in method , passing scanner method well, here main method:
scanner scan = new scanner(system.in); system.out.println("length:"); int length = 0; if(scan.hasnextint()){ length = scan.nextint(); } if(length<0 || length>100){ system.out.println("length not of proper size"); scan.close(); return; } double[] a1 = new double[length]; double[] a2 = new double[length]; fillwithzeros(a1); fillwithzeros(a2); system.out.println("enter numbers multiplied:"); a1 = fillwithvalues(a1,scan); a2 = fillwithvalues(a2,scan); double total = calculatetotal(a1,a2); printvector(a1,"a1"); printvector(a2,"a2"); system.out.println("total: " + total); scan.close();
then here fillwithvalues method:
public static double[] fillwithvalues(double[] array, scanner scan) { int numberofelements = 0; while(scan.hasnextdouble()){ if(numberofelements<array.length){ array[numberofelements] = scan.nextdouble(); numberofelements++; }else{ return array; } } return array; }
the issue having when press control-d doesn't end input stream should, have code above in main end input stream, explain why having issue?
i declare scanner global variable not allowed use global variables assignment.
in code above, using
a1 = fillwithvalues(a1,scan); a2 = fillwithvalues(a2,scan);
where fillwithvalues()
does
while(scan.hasnextdouble()){ ... }
that means, if scanner observes eof character (ctrl-d
in case of unix), scan.hasnextdouble()
return false
, method terminate - however, program calls method again scanner wait next double (if press ctrl-d
again program should terminate in case also).
if replace two method calls one invocation of loop, programm resume after (first only) loop , terminate.
to solve that, can let method return boolean
instead of array (you not need return , re-assign array return value since modifying array elements of array passing parameter):
public static boolean fillwithvalues(double[] array, scanner scan) { int numberofelements = 0; while(scan.hasnextdouble()){ if(numberofelements<array.length){ array[numberofelements] = scan.nextdouble(); numberofelements++; }else{ return true; // elements read } } return false; // input aborted }
the calling code can decide whether terminate or continue:
if (fillwithvalues(a1,scan) == true) { fillwithvalues(a2,scan); // check return value again if required }
btw, use static
methods when absolutely required - there no need here. should take excercise remove static
method, once overall logic works fine.
Comments
Post a Comment