I have to implement a program using the Stack class which allows a user to enter a positive integer,n
, followed by n
integers. Then the program should allow the user to enter another integer, val
after which the program should display the last value which is greater than val
.
From my understanding of the program, I figured out that it should compare each element from the top of the stack to the val
. Therefore to compare each element to val
, it should iterate through the values in the stack starting from the top. I don't really know how to make this work so would be pleased if I could get any help.
Here is my program:
import java.util.*;
public class MyClass{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
Stack<Integer> NumsInStack= new Stack<Integer>();
int n, num, val;
System.out.println("Please enter n.");
n=sc.nextInt();
for(int i=0; i<n;i++){
num=sc.nextInt();
NumsInStack.push(num);
}
System.out.println("Enter a value.");
val=sc.nextInt();
for(int i=0; i<NumsInStack.size();i++){
if(NumsInStack.peek()>val)
System.out.println("The number greater than "+val+" is "+NumsInStack.peek());
}
}
}