简体   繁体   中英

Sum a user determined amount of int and divide the result on their total amount

I am in the first week of my Java studies and I have to make a program that sums an user defined amount of numbers and then divide them to the amount of numbers given(average value).Then the user has to input the numbers separately one by one and the program has to put them in order when asking(Number 1: ; Number 2: ; etc). The thing is that I can only use loops: for, while; conditions: if ;switch and util.Scanner ! No arrays no packages no other functions :(.

First thing I thought was this but on every loop the value of the variable changes and there is no way to sum with the next/previous value.

    import java.util.Scanner;
        Scanner in= new Scanner(System.in);
        for(count=1;count<=numberAmount;count++){
            System.out.println("Number"+count+" :");
            int number=Integer.parseInt(in.nextLine());
        }
    }
}

If you are not required to print back each of the number entered, then you can just sum it everytime user enter the number.

Scanner in= new Scanner(System.in);
System.out.println("How many number?")
int numberAmount = Integer.parseInt(in.nextLine());
int sum=0;
int average=0;

for(count=1;count<=numberAmount;count++){
    System.out.println("Number"+count+" :");
    sum+=Integer.parseInt(in.nextLine());
}

average = sum / numberAmount;
System.out.println("The average of " +numberAmount+" entered number(s) is "+average);
import java.util.Scanner;
Scanner in= new Scanner(System.in);
int number = 0;
for(count=1;count<=numberAmount;count++){
    System.out.println("Number"+count+" :");
    number += Integer.parseInt(in.nextLine());
}
}
} 

Declare the variable outside the loop to use as sum

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