0
嗨,大家好我有一个真正的困难时间,试图让这段代码解决。我的指导线为:要求用户输入数字,获取最小/最大/平均值
- 创建一个新的Scanner对象,并把它保存到你选择
- 的变量名声明一个整型变量当前用户的输入,并把它初始化的东西,是不为0(我们将尽管如此,将它命名为intInput - 名称是任意的)虽然
- 创建一个while循环,条件是intInput不等于0
- 在此循环的内部,调用Scanner的nextInt()方法对象并将其存储到intInput中
我没有得到任何错误,但它没有按照我认为的那样工作。
这里是我的代码:
import java.util.Scanner;
// class name matches the file name
public class Lab5
{
// we must have a main method to run the program
`enter code here`public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
int userInput = 1;
int minVal = Integer.MIN_VALUE;
int maxVal = Integer.MAX_VALUE;
double average = 0;
int holdNum = 0;
double numSum = 0;
System.out.print ("Please enter numbers and to finish the program your last number should be 0: ");
numSum += userInput;
holdNum++;
while (userInput != 0)
{
userInput = scan.nextInt();
}
if (maxVal > Integer.MAX_VALUE)
{
maxVal = userInput;
}
if (minVal < Integer.MIN_VALUE)
{
minVal = userInput;
}
average = (numSum)/(holdNum);
System.out.println("Average = " + average);
System.out.println("Max = " + maxVal);
System.out.println("Minimum = " + minVal);
}
}
对不起,我发布后,我睡着了。谢谢(你的)信息 。我将总和和递增移动到我的印刷品的正下方,告诉用户该做什么。我仍然没有得到正确的数字。我分别输入1,2,3,4,0。我的平均值是1.0(应该是2),最大值是2147483647,最小值是-2147483648。任何进一步的帮助将不胜感激。 –
您使用Integer.MIN_VALUE作为初始最小值。没有整数小于这个值,所以初始值永不改变。初始最大值也会发生同样的情况:没有整数大于Integer.MAX_VALUE。至于平均水平,你能否更新问题中的代码?就目前而言,它会在循环的每次运行中打印平均值。 – Joni
对不起,有一个课程不允许笔记本电脑出来。现在我有一个免费的小时工来处理这个问题。 –