我怎么知道从堆栈弹出的对象是什么?

时间:2017-09-21 08:19:10

标签: java class stack pop

所以,我有两种类型:数字和操作。我把数字和操作符中的所有数字都放在我的堆栈中。

当我从堆栈中弹出时,如何知道它是否返回数字或运算符?

我需要知道我是否按顺序弹出了两个数字和运算符。

所以我有两个课程:numberNodeoperationNode。我使用Scanner在if语句中输入数字和操作。 例如,如果它是一个数字,我把stack.push(new numberNode(Scanner.nextInt()));放得像这样。

然后,我需要检查我是stack.pop(),无论是操作员还是数字。

2 个答案:

答案 0 :(得分:0)

element instanceof numberNode
如果element是numberNode

,则

返回true

答案 1 :(得分:0)

定义一个Stack类,它可以是一个数字或一个操作,让它安全的类型。 在弹出之前,用.gettype(); (可能是一个字符串)它是什么样的东西,并且用

安全
private boolean foundOrder = false;
private boolean twoNumbers = false;
private String firstItem,secondItem;
while(!foundOrder && !stack.empty()){
    if(stack.getData().getType().equals("number")){
        firstItem = stack.getData().getType(); //"write the Name on a paper"
        stack.pop(); //dump the thing away
        if(stack.getData().getType().equals("number")){ 
            //you found 2 types which are the same
            secondItem = stack.getData().getType();
            stack.pop();
            twoNumbers = true;
            while(twoNumbers && !foundOrder){
                if(stack.getData().getType().equals("opperation")){
                foundOrder = true;
                } else {
                    stack.pop();
                }
            }
        } else {
            //number object and you start again
        }
    } else {
        //its an operation
    }
}
//If you land here it has found your order or stack is empty!
if(foundOrder){
    //we found your order
} else {
    //stack is empty and your order wasn´t in the stack
}

这只是一种示意性的代码,只是为了给你一个提示,你可以在谷歌进行短期研究后做些什么。你也可以这样做:))

Class myClass{
private int number;
private String opperation,type;

public myClass(int n){
setNumber(n);
}
public myClass(String s){
setOpperation(s);
}
enter code here
private void setNumber(int n){
this.number = n;
this.type = "number";
}

private void setOpperation(String s){
this.opperation = s;
this.type = "opperation";
}
public string getType(){
return type;
}
}