max - using scanner class to average numbers in java -
i using scanner class average numbers together. using method averaging. not want program run if there more 20 args. cant seem work. new @ java , trying learn.
i appreciate can get. thanks!
import java.util.scanner; class programtwo { public static void main (string[] args) { scanner scan = new scanner(system.in); double x = 0.00d; if (args != null) { system.out.println ("enter numbers averaged. remember no more 20!:"); x = scan.nextint(); if (x <= 21) { system.out.println("please not add more 20 numbers"); } } else { } } public double average(double [] values) { double average = 0.0; if ((values != null) && (values.length > 0)) { (double value : values) { average += value; } average /= values.length; } return average; } }
here solution (cleaning lot of code well) gets numbers on 1 line after start of program:
import java.util.scanner; class programtwo { public static void main (string[] args) { scanner scan = new scanner(system.in); double values[] = new double[20]; int count = 0; system.out.println ("enter numbers averaged. remember no more 20!:"); string inputs = scan.nextline(); scan = new scanner(inputs); // create new scanner out of our single line of input while(scan.hasnextdouble()) { if(count == 20) { system.out.println("you entered many numbers! fail."); return; } values[count] = scan.nextdouble(); count += 1; } system.out.println("your average is: " + average(values, count)); } public static double average(double [] values, int count) { double average = 0.0; (double value : values) { average += value; } average /= count; return average; } }
i got thinking might want use args passed main, since use null check, want run program this:
java programtwo num1 num2 num3 num4 num5
etc. if that's case, have solution:
class programtwo { public static void main (string[] args) { if(args.length > 20) { system.out.println("you entered many numbers! fail."); return; } double values[] = new double[args.length]; for(int i=0; i< args.length; ++i) values[i] = double.valueof(args[i]); system.out.println("your average is: " + average(values)); } public static double average(double [] values) { double average = 0.0; (double value : values) { average += value; } average /= values.length; return average; } }
Comments
Post a Comment