我有一個程序經過並讀取「令牌」,可以是字符串(符號)或數字。它使用postfix和一個堆棧來評估簡單的命令。進入「if」語句的問題,JAVA
例如:
/x 100 def
/y 200 def
x y add
應返回300的第一行定義了一個名爲「×」的變量,將其設爲100。爲了做到這一點的讀取器將「/ x」和「100」的堆棧並在到達「def」運算符時停止,該運算符告訴它使用一個名爲「x」的符號創建一個令牌,其值爲100.該堆棧然後爲空,下一次「x」將被推入,解釋者應該自動用它的值替換它。這是我的問題所在。
這是我的翻譯:
while (r.hasMoreTokens()) {
Token t = r.nextToken();
if (!t.isSymbol()) {
operands.push(t);
} else if (env.contains(t.getSymbol())) {
Token tmp = env.get(t.getSymbol());
operands.push(tmp);
} else if (t.getSymbol().startsWith("/")) {
operands.push(t);
} else if (t.getSymbol().equals("def")){
execute_def();
} else if (t.getSymbol().equals("add")) {
execute_add();
} else if (t.getSymbol().equals("sub")) {
execute_sub();
} else if (t.getSymbol().equals("mul")) {
execute_mul();
} else if (t.getSymbol().equals("exch")) {
execute_exch();
} else if (t.getSymbol().equals("dup")) {
execute_dup();
} else if (t.getSymbol().equals("pop")) {
execute_pop();
} else if (t.getSymbol().equals("pstack")) {
execute_pstack();
} else if (t.getSymbol().equals("moveto")) {
execute_moveto();
} else if (t.getSymbol().equals("lineto")) {
execute_lineto(g);
} else if (t.getSymbol().equals("arc")) {
execute_arc(g);
} else if (t.getSymbol().equals("quit")) {
execute_quit();
} else {
System.out.println("ILLEGAL SYMBOL: " + t);
}
}
一旦變量得到正確定義,我不能進入,首先else if
和改變數值。因爲我無法做到這一點,所以我從不在堆棧上推動任何東西,最終導致堆棧錯誤。這裏有方法和ENV get()
(環境):
public boolean contains(String key) {
Elem tmp = top;
for (int i = 0; i < size; i++) {
if (tmp.key == key) {
return true;
} else {
tmp = tmp.next;
}
}
return false;
}
public Token get(String key) {
Elem tmp = top;
int counter = 0;
boolean found = false;
for (int i = 0; i < size; i++) {
if (tmp.key == key) {
found = true;
break;
} else {
tmp = tmp.next;
}
counter++;
}
if (found == true) {
tmp = top;
for (int i = 0; i <= counter; i++) {
tmp = tmp.next;
}
return tmp.value;
} else {
throw new BadKeyQueryException();
}
}
我使用環境中的鏈接的元素來跟蹤符號。 ELEM是一個嵌套類環境:
private static class Elem {
private String key;
private Token value;
private Elem next;
private Elem(String key, Token value, Elem next) {
this.key = key;
this.value = value;
this.next = next;
}
}
感謝來自你們的幫助!
永遠不要用==比較字符串,而是使用.equals。 – I82Much 2011-03-17 04:20:28
謝謝l82Much,我現在有一套新的錯誤需要處理。 爲什麼你永遠不會比較字符串與==? – n0pe 2011-03-17 04:22:46
應用於對象的'=='測試左側和右側對象是否是同一個對象。所以''abc「== new String(」abc「)'是** false **。儘管如此,我不會說「從不」;有時可能會出現這種情況。但「幾乎從不」就是正確的。:) – 2011-03-17 04:46:22