Answer:
Here is the program that reads a list of integers, and outputs those integers in reverse.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] userList = new int[20]; // List of numElement integers specified by the user
int numElements; // Number of integers in user's list
numElements = scnr.nextInt(); // Input begins with number of integers that follow
// Read integers into array
for (int i = 0; i < numElements; i++) {
userList[i] = scnr.nextInt();
}
// Output integers in reverse
for (int i = numElements - 1; i >= 0; i--) {
System.out.print(userList[i] + " ");
}
}
}
Step-by-step explanation:
This Java program takes input from the user via the console, and then reverses the order of the integers entered by the user and prints them out in the console.
Here is a more detailed explanation of how this code works:
- The program first imports the Scanner class from the java.util package, which allows the program to read user input from the console.
- It then defines a public class called "LabProgram" with a main method that takes an array of Strings as an argument.
- In the main method, a new Scanner object named "scnr" is created to read user input from the console.
- The program creates an integer array called "userList" with a length of 20. This will be used to store the list of integers entered by the user.
- The program creates an integer variable called "numElements" to store the number of integers that the user will enter.
- The program reads in the first integer entered by the user using the "nextInt()" method of the Scanner object, and assigns it to "numElements".
- The program then enters a loop that reads in the rest of the integers entered by the user, and stores them in the "userList" array. The loop runs "numElements" times, and at each iteration, the program reads in an integer using the "nextInt()" method of the Scanner object and assigns it to the corresponding element of the "userList" array.
- Once all the integers have been read in and stored in the "userList" array, the program enters another loop that starts from the last element of the array and prints out each integer in reverse order, separated by a space. The loop runs from "numElements-1" to 0, and at each iteration, it prints out the integer stored in the corresponding element of the "userList" array using the "print()" method of the System.out object.
- Once all the integers have been printed out in reverse order, the program terminates.