In: Computer Science
Question 3 - If Statements - Intermediate
Put your ducks in a row. If ye dare.
Boolean comparisons provide the basis for that entire (critically important) 'sorting' category of operations (specifically, comparison sorting). Comparison sorts are those methods of organizing data in which one element is compared against another, and the relative position of one or both elements is determined by the comparison result.
TASK:
Based upon the following code:
import java.util.Scanner; // Import the Scanner class public class Main { public static void main( String[] args ) { Scanner myInput = new Scanner(System.in); // Create a Scanner object System.out.println("Enter (3) digits: "); int W = myInput.nextInt(); int X = myInput.nextInt(); int Y = myInput.nextInt();
} } |
Use the tools described thus far to create additional code that will sort the integers in either monotonic ascending or descending order. Copy your code and output below:
import java.util.Scanner; // Import the Scanner class public class Main { public static void main( String[] args ) { // Create a Scanner object Scanner myInput = new Scanner(System.in); // Accept the user's input System.out.println("Enter (3) digits: "); int W = myInput.nextInt(); int X = myInput.nextInt(); int Y = myInput.nextInt(); // <TODO> - Sort the integers int first = 0; int second = 0; int third = 0; // Report the sorted numbers System.out.println( "The sorted values are:" ); System.out.println( first + " " + second + " " + third); } } |
<TODO - Program output> |
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main( String[] args ) {
// Create a Scanner object
Scanner myInput = new Scanner(System.in);
// Accept the user's input
System.out.println("Enter (3) digits: ");
int W = myInput.nextInt();
int X = myInput.nextInt();
int Y = myInput.nextInt();
// Sort the integers
int first = 0;
int second = 0;
int third = 0;
if(W<X){
if(W<Y){
first = W;
if(X<Y){ // W<X<Y
second = X;
third = Y;
}
else{ // W<Y<=X
second = Y;
third = X;
}
}
else{
// Y<=W<X
first = Y;
second = W;
third = X;
}
}
else if(X<Y){
first = X;
if(W<Y){ //
X<=W<Y
second = W;
third = Y;
}
else{
// X<Y<=W
second = Y;
third = W;
}
}
else{
// Y<=X<=W
first = Y;
second = X;
third = W;
}
// Report the sorted numbers
System.out.println( "The sorted values are:" );
System.out.println( first + " " + second + " " + third);
}
}
Sample output 1
Sample output 2
Sample output 3
Sample output 4
Sample output 5