Answer:
import java.util.Scanner;
public class NumberInputProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
boolean continueProgram = true;
while (continueProgram) {
System.out.println("Enter a number (enter 0 to terminate):");
int number = scanner.nextInt();
if (number == 0) {
System.out.println("Terminating input loop...");
continueProgram = false;
} else {
if (number > largest) {
largest = number;
}
if (number < smallest) {
smallest = number;
}
}
}
System.out.println("Largest number entered: " + largest);
System.out.println("Smallest number entered: " + smallest);
System.out.println("Do you want to enter a new set of numbers? (yes/no)");
String answer = scanner.next();
if (answer.equalsIgnoreCase("yes")) {
main(args); // Recursive call to restart the program
} else {
System.out.println("Exiting the program...");
}
scanner.close();
}
}
Step-by-step explanation:
- The program utilizes nested loops: an outer loop that runs until told to stop and an inner loop that asks for number input until 0 is entered.
- Inside the inner loop, the program checks if the entered number is the largest or smallest so far.
- When the inner loop terminates (by entering 0), the program displays the largest and smallest numbers.
- Afterward, the program asks the user if they want to enter a new set of numbers. If the answer is "yes," the program restarts by calling the `main()` method recursively. Otherwise, the program exits.
You can run this program, enter numbers (positive or negative), and observe the largest and smallest numbers displayed. You can choose to enter a new set of numbers if desired.