我需要接受用户输入,并让程序通过所有方法和东西来运行它,以输出最大和最小的数字。我可以打印最大的它,但是它总是最小的为0。这可能很容易修复,但这是本季度末,我强调要完成最后一个。这是我的代码。
import java.io.*;
import java.util.*;
public class P4_6
{
private int sum;
private int count;
private int largest = Integer.MIN_VALUE;
private int smallest = Integer.MAX_VALUE;
public P4_6()
{
sum = 0;
largest = 0;
smallest = 0;
count = 0;
}
public void addValue(int x)
{
smallest = Math.min(smallest, x);
largest = Math.max(largest, x);
sum = sum + x;
count++;
}
public int getSum()
{
return sum;
}
public int getLargest()
{
return largest;
}
public int getSmallest()
{
return smallest;
}
public static void main(String[] args)
{
Scanner kbreader = new Scanner(System.in);
System.out.println("Enter your first integer: ");
int num1 = kbreader.nextInt();
System.out.println("Enter your second integer: ");
int num2 = kbreader.nextInt();
System.out.println("Enter your third integer: ");
int num3 = kbreader.nextInt();
System.out.println("Enter your fourth integer: ");
int num4 = kbreader.nextInt();
P4_6 data = new P4_6();
data.addValue(num1);
data.addValue(num2);
data.addValue(num3);
data.addValue(num4);
System.out.println("The largest was " + data.getLargest());
System.out.println("The smallest was " + data.getSmallest());
}
}
答案 0 :(得分:0)
您不需要使用无参数构造函数。 Java编译器默认添加No-argument构造函数。您可以删除以下部分。
public P4_6()
{
sum = 0;
largest = 0;
smallest = 0;
count = 0;
}
如果您希望将此部分保留在代码中,则应按如下所示初始化变量
public P4_6()
{
sum = 0;
largest = Integer.MIN_VALUE;
smallest = Integer.MAX_VALUE;
count = 0;
}
答案 1 :(得分:0)
您不需要初始化“最小”和“最大”。只需删除它们
public Test()
{
sum = 0;
//largest = 0;
//smallest = 0;
count = 0;
}