我得到了这个问题,我试了好几次,没有想到任何事情:(
这是一个问题:设计并编写一个程序来输入10个人的权重。它应该只接受20公斤到100公斤之间的重量。你的程序应该计算并打印这些人的平均,最大和最小权重。
这是我试过的代码。任何人都可以完成这个或提出简化的代码吗?这是正确的,我的意思是我这样做的方式?请帮忙
import java.util.Scanner;
class WeightOfPeople{
public static void main(String args []){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a weight between 20kg - 100kg :");
int weight1 = sc.nextInt();
if(20 < weight1 && weight1 < 100){
System.out.print("Enter a weight between 20kg - 100kg :");
int weight2 = sc.nextInt();
}else{
System.out.println("Enter a correct weight");
}
}
答案 0 :(得分:1)
试试这个:
Scanner sc = new Scanner(System.in);
int count = 0;
int total = 0;
int min = 101;
int max = 19;
while(count < 3) {
System.out.print("Enter a weight between 20kg - 100kg :");
int nextWeight = sc.nextInt();
if(20 <= nextWeight && nextWeight <= 100){
total += nextWeight;
if(nextWeight < min) {
min = nextWeight;
}
if(nextWeight > min) {
max = nextWeight;
}
count++;
}
else{
System.out.println("Enter a correct weight");
}
}
System.out.println("Average = " + ((double)total/count));
System.out.println("Min = " + min);
System.out.println("Max = " + max);
答案 1 :(得分:0)
您希望用户能够输入 10个不同的值。因此,您需要某种循环。
e.g。
for (int i = 0 ; i < 10 ; i++) {
System.out.print("Enter a weight: ");
// record users input
}
我要做的是维护一个整数数组来存储用户输入的所有数据。收集数据后,您可以循环此数组以确定最小值,最大值和平均值。像这样:
int min = weights[0];
int max = weights[0];
double avg = 0;
for (int weight : weights) {
if (weight < min)
min = weight;
if (weight > max)
max = weight;
avg += weight;
}
avg /= weights.length;
总的来说,你会有这样的事情:
Scanner in = new Scanner(System.in);
int[] weights = new int[10];
for (int i = 0 ; i < 10 ; i++) {
System.out.print("Enter a weight between 20 and 100: ");
weights[i] = in.nextInt();
}
in.close();
int min = weights[0];
int max = weights[0];
double avg = 0;
for (int weight : weights) {
if (weight < min)
min = weight;
if (weight > max)
max = weight;
avg += weight;
}
avg /= weights.length;
System.out.println("Min: " + min);
System.out.println("Max: " + max);
System.out.println("Average: " + avg);
答案 2 :(得分:0)
public static void main(String args []){
Scanner sc = new Scanner(System.in);
int i = 0;
int sum = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
do{
System.out.print("Enter a weight between 20kg - 100kg :");
int weight = sc.nextInt();
if(20 <= weight && weight <= 100){
sum += weight;
if(weight<min){
min = weight;
}
if(weight>max){
max = weight;
}
i++;
}
else {
System.out.println("Enter a correct weight");
}
} while(i<=10)
System.out.println("AVG "+ (sum/10)+" Min "+ min +" Max "+max);
}