I'm making a simple program that takes input for 3 integers (n1, n2, n3) so for example if the 3 numbers were 6,12,4 it should return:
Integers entered: 6,12,4
Sum = 22
Average = 7.33...
Smallest = 4
Largest = 12
This is displayed in a text box using JOptionPane.showMessageDialog. The code is put in a loop so that for every 3 integers entered, it will return the whats shown above. However when I run the program it shows the following:
Integers entered: 6,6,6
Sum = 22
Average = 7.33...
Smallest = 6
Largest = 6
the values for n2,n3, smallest and largest show the value for n1. Here's the code inside the loop that's giving me problems:
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);
How do I fix it so that n2,n3,smallest,largest display their correct values?
Your assigning the value of smallest
and largest
back into n2
or n3
, depending on the result of the evaluation...
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;
Try something more like...
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;