java - using a while loop for user to input multiple int and find the max and min -
so homework question prompt user series of integers , find max , min of integer. use loop , -99 break loop.below code question is there shorter way this? feel free comment , appreciate time reading this.
scanner input=new scanner(system.in); int num1,num2,max,min; system.out.print("enter number: "); num1=input.nextint(); system.out.print("enter number: "); num2=input.nextint(); max=math.max(num1,num2); min=math.min(num1,num2); while (num2!=-99){ system.out.print("enter number or -99 stop: "); num2=input.nextint(); if(num2!=-99){ max=math.max(max,num2); min=math.min(min,num2); } } system.out.println("largest is: "+max); system.out.println("smallest is: "+min);
ok after working on this. did it. have small bug, don't wanna fix if anyway wants edit guest.
scanner input = new scanner(system.in); int studentnum = 0; arraylist<integer> calc = new arraylist<integer>(); while (studentnum <= 100) { system.out.print("enter number: "); calc.add(input.nextint()); studentnum += 1; if (input.nextint() == -99) { break; } } int min = collections.min(calc); int max = collections.max(calc); (int = 0; < calc.size(); i++) { int number = calc.get(i); if (number < min) min = number; if (number > max) max = number; } system.out.println("max " + max); system.out.println("min " + min);
this want. however, there problem checking exit signal.
if (input.nextint() == -99) { break; }
this checks if userinput equal -99 stops program , calculates , prints out min , max. tiny bug first ask number add array list , ask again userinput check if equal -99. overall want.
hope helped.
edit work on later , find way fix bug if no 1 else knows.
Comments
Post a Comment