Please use String class. 1. Write a Java program that will ask the user to enter
ID: 3586550 • Letter: P
Question
Please use String class.
1. Write a Java program that will ask the user to enter four integer numbers and find the greatest and the smallest of these numbers. The program will then ask the user to enter the choice: 1 (for greatest) and 2 (for smallest). Based on the entered choice, the program displays the greatest or the smallest of these four numbers Sample output is as follows Number 1: 24 Number 2:10 Number 3: 55 Number 4:-10 Enter 1 (for greatest) and 2 (for smallest):2 The smallest of these four numbers is -10Explanation / Answer
FourNumbers.java
import java.util.Scanner;
public class FourNumbers {
public static void main(String[] args) {
int a[]= new int[4];
Scanner scan = new Scanner(System.in);
for(int i=0;i<a.length; i++) {
System.out.print("Number "+(i+1)+": ");
a[i] = scan.nextInt();
}
String prompt = "Enter 1(for greatest) and 2(for smallest): ";
System.out.print(prompt);
int choice = scan.nextInt();
if(choice == 1) {
System.out.println("the greatest of the four numbers: "+getMax(a));
} else {
System.out.println("the smallest of the four numbers: "+getMin(a));
}
}
public static int getMax(int a[]) {
int max = a[0];
for(int i=0;i<a.length;i++) {
if(max < a[i]) {
max = a[i];
}
}
return max;
}
public static int getMin(int a[]) {
int min = a[0];
for(int i=0;i<a.length;i++) {
if(min > a[i]) {
min = a[i];
}
}
return min;
}
}
Output:
Number 1: 24
Number 2: 10
Number 3: 55
Number 4: 10
Enter 1(for greatest) and 2(for smallest): 2
the smallest of the four numbers: 10