43.1k views
4 votes
Write in Java for thumbs up.

Your program must prompt the user to input 4 string items. Example input: Enter four items,
separated by a space: Fred Jane Marv Steve he output is: Stack: [Fred, Jane, Marv, Steve] Stack
after first item popped: [Fred, Jane, Marv] Stack after second item popped: [Fred, Jane].

User Arvindh
by
8.3k points

1 Answer

6 votes

Final answer:

The student's question involves writing a Java program that simulates a stack using 4 string inputs. The program prompts the user for input, creates a stack, and performs two pop operations to display the stack's state each time an item is removed.

Step-by-step explanation:

The student has asked for a Java program that prompts the user to input 4 string items, then processes this input like a stack. A stack is a data structure that follows the last-in-first-out (LIFO) principle. In this case, we will assume the last inputted item is considered the top of the stack. The user is instructed to enter these items separated by a space. The program will then output the stack and show the stack after each pop operation (which removes the last item entered).

Example Java Program

import java.util.Scanner;
import java.util.Stack;

public class StackExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Stack<String> stack = new Stack<>();
System.out.print("Enter four items, separated by a space: ");
for(int i = 0; i < 4; i++) {
stack.push(scanner.next());
}
System.out.println("Stack: " + stack);
stack.pop();
System.out.println("Stack after first item popped: " + stack);
stack.pop();
System.out.println("Stack after second item popped: " + stack);
scanner.close();
}
}

By running this program, the user will be able to see the stack's contents after each pop operation, as requested.

User John Wigger
by
8.7k points