Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Java program with String class that will ask the user to enter four inte

ID: 3586723 • Letter: W

Question

Write a Java program with String class 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 -10

For documentation, I don’t expect you to add comment in each line, but you must explain the code appropriately.

Explanation / Answer

FourNumbers.java

import java.util.Scanner;

public class FourNumbers {

public static void main(String[] args) {

int a[]= new int[4];//array size is 4

Scanner scan = new Scanner(System.in);

for(int i=0;i<a.length; i++) {//reading 4 numbers

System.out.print("Number "+(i+1)+": ");

a[i] = scan.nextInt();//assigning the value

}

String prompt = "Enter 1(for greatest) and 2(for smallest): ";

System.out.print(prompt);

int choice = scan.nextInt();//reading the choice

if(choice == 1) {//printing the max

System.out.println("the greatest of the four numbers: "+getMax(a));

} else {//printing the min

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote