Error when trying to find minimum of java code with no known amount of integers -
i have make code takes in unknown amount of user input integers, finds min , max, , finding average of integers. have far.
package hw2_min_max; import java.util.scanner; public class hw3 { public static void main(string[] args) { scanner myscanner = new scanner(system.in); system.out.println("please input first interger"); int number=0; //number store number of inputs int i=1; //i store current iteration int sum=0; //sum store sum of input int x=0; //x store user input int min=x, max=x; number = myscanner.nextint(); if(x>=0) while (x >= 0){ system.out.println("please input next positive interger "); x = myscanner.nextint(); sum = sum + x; number = number++; if (x >= max) max = x; if (x <= min) min =x; i++; } int average = sum/number; system.out.println("the average " + average); system.out.println("the minimum value " + min); system.out.print( "and maximum value " + max); } }
it runs fine , want do, condition gave end program negative number. output max comes out right, negative affects average , minimum. can't figure way minimum end program , not entered values.
there issues in code. first scanned integer value ignore in calculation. , min value 0 because 'int min = 0' did changes on code try this.
public static void main(string[] args) { scanner myscanner = new scanner(system.in); system.out.println("please input first integer"); int number = 0; //number store number of inputs int sum = 0; //sum store sum of input int x; //x store user input int min = integer.max_value, max = 0; x = myscanner.nextint(); while (x >= 0) { sum = sum + x; number++; if (x >= max) { max = x; } if (x <= min) { min = x; } system.out.println("please input next positive integer "); x = myscanner.nextint(); } int average = sum / number; system.out.println("the average " + average); system.out.println("the minimum value " + min); system.out.print("and maximum value " + max); }
Comments
Post a Comment