1
所以我有一個我建立的堆棧,我有一臺機器評估表達式,如(9 + 0),他們可以更復雜。我運行它有趣的命令行,然後當我鍵入示例(9 + 5)該程序就坐在那裏。我可以得到一個新行,但表達式不評估。所以我的問題是我錯過了什麼。我確信有些東西我沒有正確理解,並且我一直在想我缺少一些關於Scanner或Java中的數組的知識。堆棧添加機器不添加,但掛起等待更多的參數
也許我昨天晚上在想,我應該用ArrayList替換數組。這有意義嗎?
這裏是固定容量堆疊
public class FCStack<Item> {
private Item[] a;
private int top; // pointer to top of Stack
private int capacity; // size of the Stack+1
public FCStack(int cap){
capacity = cap;
a = (Item[]) new Object[capacity];
top = 0;
}
public void push(Item i){ //will only push an Item to the Stack if there is room.
if (!isFull()) {
a[top++] = i;
}
}
public Item pop(){ //will only pop an Item from the stack if there is something to pop.
if (!isEmpty()) {
--top;
}
return a[top];
}
public boolean isFull(){ //returns true if is full
return top == capacity;
}
public boolean isEmpty(){ //returns true if is empty
return top == 0;
}
public int size(){ //returns the current size of the stack+1 or the array index
return top;
}
}
下面是兩個堆棧評價
import java.io.*;
import java.util.Scanner;
public class TwoStackMaths {
public static void main (String[] args) {
FCStack<String> ops = new FCStack<String>(10);
FCStack<Double> vals = new FCStack<Double>(10);
Scanner console = new Scanner(System.in);
while(console.hasNext()) {
String str = console.next();
if (str.equals("("))
;
else if (str.equals("+")) {
ops.push(str);
}
else if (str.equals("-")) {
ops.push(str);
}
else if (str.equals("*")) {
ops.push(str);
}
else if (str.equals("/")) {
ops.push(str);
}
else if (str.equals("^")) {
ops.push(str);
}
else if (str.equals(")")) {
String op = ops.pop();
double v = vals.pop();
if (op.equals("+")) {
v = vals.pop() + v;
}
else if (op.equals("-")) {
v = vals.pop() - v;
}
else if (op.equals("*")) {
v = vals.pop() * v;
}
else if (op.equals("/")) {
v = vals.pop()/v;
}
else if (op.equals("^")) {
v = Math.pow(v, vals.pop());
}
vals.push(v);
}
else {
vals.push(Double.parseDouble(str));
}
}
//console.close();
System.out.println(vals.pop());
}
}
嘗試按CTRL-d來結束你的控制檯輸入。或者添加一個命令來顯示! –
您是否試圖在調試器中逐步運行您的代碼? –