简体   繁体   中英

I can't find smallest number by this code. How I find smallest number by modifying this code?

Nothing additional errors. I just can't print the smallest input.

public static void main(String args[]){
    Scanner input=new Scanner(System.in);
    System.out.print("Marks of a student(-1 to terminate the inputting marks): ");
    int x=input.nextInt();
    int total=0,large=0,y=0,small=0,z;
    z=x;
    while(x!=-1){
        System.out.print("Marks of a student(-1 to terminate the inputting marks): ");
        x=input.nextInt();
        total+=x;
        y++;
        if(x>=large){
            large=x;
        }
        if(x<small){
            small=x;
        }
    }
    int sum=total+z+1;
    double avg=(double)total/y;
    System.out.println("No of students: "+y);
    System.out.println("Total marks   : "+sum);
    System.out.println("Maximum       : "+large);
    System.out.println("Minimum       : "+small);
    System.out.println("Average       : "+avg);
}

small is initialized with 0 , so any input larger than that would be ignored.

One approach is to initialize it with Integer.MAX_VALUE , so any inputted number would be smaller or equal to it. Similarly, large could be initialized with Integer.MIN_VALUE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM