java - How to handle invalid input when using Scanner.nextInt() -
i beginner , wrote java program allows enter n numbers , displays max, min , average if number -5 entered, program not displaying correctly , need help. want use try/catch catch errors when string entered instead integer.
import java.util.scanner; public class average{ public static void main(string[]args){ system.out.print("enter integer numbers or -5 quit:"); scanner scan =new scanner(system.in); double avg = 0.0; int number = -1; double avg = 0.0; double sum = 0; int count = 0; int min = integer.max_value; int max = integer.min_value; try { while((scan.nextint())!= -5) { if (count != 0) { avg = ((double) sum) / count; count++; } if (number > max){ max = number; } if(number < min){ min = number; } catch (inputmismatchexception e) { system.out.println("please enter integer numbers"); system.out.println("average : " + avg); system.out.println("maximum : " + max); system.out.println("minimum : " + min); } } } } }
you want
if(number > max) { max = number; } if(number < min) { min = number; }
inside while loop because right checking last read value(also, there's no need counter outisde loop(after have read -5, btw, why -5?o.o).
also, want min/max values initialised way, because if min value bigger 0, code outputs 0. same goes if max value below 0:
int min = integer.max_value; int max = integer.min_value;
for non-integer part: read on exceptions , use try-catch
block catch inputmismatchexception.
try { //while(scan.nextint) here } catch (inputmismatchexception e) { //do here, print in console }
as else pointed out, if want average not truncated, cast sum double: ((double) sum) / count
.
finally, important: try debugging before asking else.
Comments
Post a Comment