In: Computer Science
Assume all methods in the Stack class are available to you, request from the user a set of numbers (terminated by -1) and print them in reverse order . write code in java.
Explanation:
Here is the code which creates a Stack s and then push all the elements entered by the user until the user presses -1 , to the stack.
Then, it keeps popping the elements one by one and they get printed in the reverse direction.
Code:
import java.util.Stack;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
Stack<Integer> s = new
Stack<Integer>();
while(true)
{
System.out.print("Enter Number:
");
int n = sc.nextInt();
if(n==-1)
break;
s.push(n);
}
while(!s.empty())
{
System.out.print(s.peek()+"
");
s.pop();
}
}
}
Output:
PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!
PLEASE COMMENT IF YOU NEED ANY HELP!