我正在制作一个简单的程序,它接受3个整数(n1,n2,n3)的输入,所以例如如果3个数字是6,12,4它应该返回:
Integers entered: 6,12,4
Sum = 22
Average = 7.33...
Smallest = 4
Largest = 12
这将使用JOptionPane.showMessageDialog显示在文本框中。代码放在一个循环中,这样对于输入的每3个整数,它将返回上面显示的内容。但是,当我运行该程序时,它显示以下内容:
Integers entered: 6,6,6
Sum = 22
Average = 7.33...
Smallest = 6
Largest = 6
n2,n3,最小值和最大值显示n1的值。这是循环中的代码,它给我带来了问题:
JOptionPane.showMessageDialog(null, title);
String num1 = JOptionPane.showInputDialog("Enter 1st integer: ");
int n1 = Integer.parseInt(num1);
String num2 = JOptionPane.showInputDialog("Enter 2nd integer: ");
int n2 = Integer.parseInt(num2);
String num3 = JOptionPane.showInputDialog("Enter 3rd integer: ");
int n3 = Integer.parseInt(num3);
int sum = n1 + n2 + n3; //find sum
double avg = (double)sum/3; //find average
//find smallest integer
int smallest = n1;
if(n2 < smallest) n2 = smallest;
if(n3 < smallest) n3 = smallest;
//find largest integer
int largest = n1;
if(n2 > largest) n2 = largest;
if(n3 > largest) n3 = largest;
JOptionPane.showMessageDialog(null, "Integers entered: " + n1 + ", " + n2 + ", " + n3
+ "\nSum = " + sum
+ "\nAverage = " + avg
+ "\nSmallest = " + smallest
+ "\nLargest = " + largest);
如何修复它以使n2,n3,最小,最大显示正确的值?
您将smallest
和largest
的值分配回n2
或n3
,具体取决于评估结果......
if(n2 < smallest) n2 = smallest;
if(n3 < smallest) n3 = smallest;
//find largest integer
int largest = n1;
if(n2 > largest) n2 = largest;
if(n3 > largest) n3 = largest;
尝试更像......
if(n2 < smallest) smallest = n2;
if(n3 < smallest) smallest = n3;
//find largest integer
int largest = n1;
if(n2 > largest) largest = n2;
if(n3 > largest) largest = n3;