堆栈:如何检查每个整数(在循环中)与另一个整数?

Stack: How to check each integer(in a loop) against another integer?

我必须使用 Stack 实现一个程序,它允许用户输入一个正整数,n,然后是 n 个整数。然后程序应允许用户输入另一个整数 val,之后程序应显示大于 val 的最后一个值。根据我对该程序的理解,我发现它应该将堆栈顶部的每个元素与 val 进行比较。因此,要将每个元素与 val 进行比较,它应该从顶部开始遍历堆栈中的值。我真的不知道如何进行这项工作,所以如果我能得到任何帮助,我会很高兴。这是我的程序:

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());
        }
    }
}

你永远不应该遍历堆栈,它违背了选择该数据结构的全部目的。你想使用 poppeek:

while (!NumsInStack.empty()) {
    if (NumsInStack.peek() > val) {
        System.out.println("woot!");
        break;
    }
    NumsInStack.pop();
}

因为您只希望它打印出最后一个较大的数字,您还应该在打印语句之后放置一个 break; 以便它在找到匹配项时跳出循环。如果没有中断,它将打印所有更高的值。

工作代码:

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();

        while ( !NumsInStack.empty()){
            int stackElement = NumsInStack.pop();
            if (  stackElement > val){
                System.out.println("Stack Element > value :"+stackElement+":"+val);
                break;
            }
        }

    }
}