在我的代码中,我试图从用户输入的数字序列中找到序列的平均值、最大数和最小数。我的问题是我不知道如何编写代码,所以当用户键入 0 或负整数时停止并进行计算。
public class Sequence2
{
public static void main(String[] args)
{
Scanner keyb = new Scanner(System.in);
int count = 0;
double sum = 0;
double avg = 0;
int n;
System.out.println("Enter a sequence of positive integers, which will end with either 0 or a negative integer. ");
int max = keyb.nextInt();
int min = keyb.nextInt();
while (keyb.hasNextInt())
{
n = keyb.nextInt();
if (n > max)
{
max = n;
}
if (n < min)
{
min = n;
}
count++;
sum += n;
}
System.out.println("The maximum value is: " + max);
System.out.println("The minimum value is: " + min);
avg = sum / count;
System.out.println("Average = " + avg);
}
}
暮色呼如
慕勒3428872
饮歌长啸
慕姐8265434
相关分类