if / else statements

This program inputs two numbers and swaps them if they are not in order. A swap is a very common task in programming. Notice that you always need an extra variable to perform the swap.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package numbers;
import java.util.*;
public class Comparing {
  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in); //do just once
    int num1,num2;
    System.out.print("Enter a number:");
    num1=keyboard.nextInt();
    System.out.print("Enter another number:");
    num2=keyboard.nextInt();
    if(num1>num2) {
        int temp=num1;
        num1=num2;
        num2=temp;
    }//if out of order swap
    System.out.println("smallest is "+num1+", largest is "+num2);		
    }//main
}//class
CODE

Output:

Enter a number:5
Enter another number:9
smallest is 5, largest is 9

Enter a number:12
Enter another number:5
smallest is 5, largest is 12

NEXT: