Sorting Three Integers
| Posted in else if , if then , Java , JOptionPane | Posted on 12:24 PM
For, while, do while, if, if-then... These are all control statements. I'm at the part in my practice where loops come into play as well as controlling when instructions are executed.
The first exercise is a program which will sort three integers from largest to smallest. To do this I used a couple if and else-if statements.
/*
* This program is meant to prompt the user for
* three integers, sort those integers from
* smallest to greatest and then display
* those integers. It is also an example
* of if/else control statements.
*/
package sortingthreeintegers;
import javax.swing.JOptionPane;
/**
* @author Neil master coder
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int num1=0, num2=0, num3=0;
int smallest=0, middle=0, largest=0;
for (int i=1; i<4; i++) {
String stringNum = JOptionPane.showInputDialog(null,
"Enter integer number " + i + " to be"
+ " evaluated." );
if (i==1)
num1=Integer.parseInt(stringNum);
else if(i == 2)
num2=Integer.parseInt(stringNum);
else if(i == 3)
num3=Integer.parseInt(stringNum);
}
if ((num1<=num2) && (num1<=num3)){
smallest = num1;
if (num2<=num3){
middle=num2;
largest=num3;}
else {
largest=num2;
middle=num3;}
}
else if((num2 <= num1) && (num2 <= num3)){
smallest=num2;
if (num1
middle=num1;
largest=num3;}
}
else if((num3 <= num1) && (num3 <= num2)){
smallest=num3;
if (num2
middle=num2;
largest=num1;}
}
JOptionPane.showMessageDialog(null, "The numbers arranged "
+ "from smallest to largest are: "
+ smallest + " " + middle + " " +
largest + ".");
}
}
Comments Posted (0)
Post a Comment