You have 3 numbers as user input. WAP in Java to output their values in descending order.
Question
You have 3 numbers as user input. WAP in Java to output their values in descending order.
Solution
Here is a simple Java program that takes three numbers as input and outputs them in descending order:
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Integer[] numbers = new Integer[3];
System.out.println("Enter 3 numbers:");
for (int i = 0; i < 3; i++) {
numbers[i] = scanner.nextInt();
}
Arrays.sort(numbers, Collections.reverseOrder());
System.out.println("Numbers in descending order:");
for (int i = 0; i < 3; i++) {
System.out.println(numbers[i]);
}
}
}
Here's how this program works:
- We first import the necessary classes from the Java standard library.
- We then define a
Main
class with amain
method, which is the entry point of our program. - Inside the
main
method, we create aScanner
object to read user input. - We also create an array of
Integer
objects to store the numbers. - We then prompt the user to enter 3 numbers, and we read each number using the
nextInt
method of ourScanner
object, storing them in our array. - We then sort the array in descending order using the
sort
method of theArrays
class, passingCollections.reverseOrder()
as the comparator to sort in reverse order. - Finally, we print the numbers in descending order.
Similar Questions
What needs to go into <condition> for the code to output:234for(int num = 2; <condition>; num++) { System.out.println(num);}num <= 4num > 4num < 4num == 4
18. int value = 453;19. int d1 = value % 10;20. int d2 = (value / 10) % 10;21. int d3 = (value / 100) % 10;22. System.out.println("" + d1 + d2 + d3);23. }24. }
Develop a Java program to identify the largest among four numbers (32, 29,34, 21) using appropriate control statement and operators.
Write a program to sort integers in ascending order. Input is passed in TCL file argument.
WAP in Java to input temperature in Fahrenheit and convert it in Celsius. C= (F-32)*5/9
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.