所以我的計劃是關於語言L = {'w$w' : w
是一個字符超過$, w' = reverse(w)}
堆棧處理語言recognizng字符串,java程序
所以其他可能的空字符串時,像HOD $ DOH被送到isINlanguage函數的參數中,應該返回true,但我的程序只是停止和掛起犯規了放東西
import java.util.Stack;
public class Stacks
{
public static void main(String[] args){
boolean eval = isInLanguage("sod$dos");
System.out.println(eval);
}
static // astack.createStack();
boolean isInLanguage(String aString){
Stack<Character> aStack = new Stack<>();
int i = 0;
char ch = aString.charAt(i);
while (ch != '$') {
aStack.push(ch);
i++;
}
//Skip the $
++i;
// match the reverse of w
boolean inLanguage = true; // assume string is in language
while (inLanguage && i < aString.length()) {
char stackTop;
ch = aString.charAt(i);;
try {
stackTop = (char) aStack.pop();
if (stackTop == ch) {
i++;
} else {
// top of stack is not ch(Charecter do not match)
inLanguage = false; // reject string
}
} catch (StackException e) {
// aStack.poo() failed, astack is empty (first, half of Stirng
// is short than second half)
inLanguage = false;
}
}
if (inLanguage && aStack.isEmpty()) {
return true;
}
else{
return false;
}
}
}
這種轉換不是必需的:stackTop =(char)aStack.pop(); – TEK
不投,我得到了螺紋 「異常‘主要’java.lang.Error的:未解決的問題,編譯: \t類型不匹配:不能從對象轉換爲char \t在Stacks.isInLanguage(Stacks.java:33) \t at Stacks.main(Stacks.java:6)' – ClearMist