我是Java新手,試圖完成一個程序,該程序將讀取用戶的語句,並掃描以查看左括號的數量是否與RIGHT匹配。開始該程序的人創建了一個堆棧,但從未使用過它,所以我把它放在一邊,因爲我對堆棧不太熟悉。但是,我能夠創建一個循環來遍歷字符串中的每個字符以找到括號,比較它們,然後打印出它們是否平均。但是,我遇到了通過字符串查找所有括號的while循環的問題。由於某種原因,它不工作,我不明白爲什麼。任何解釋如何使這項工作將不勝感激。從Java中的字符串中挑選括號
import java.util.*
public class ParenMatch
{
public static void main (String[] args)
{
Stack s = new Stack();
String line; // the string of characters to be checked
Scanner scan = new Scanner(System.in);
System.out.println ("\nParenthesis Matching");
System.out.print ("Enter a parenthesized expression: ");
line = scan.nextLine();
char parenline[] = new char[line.length()];
int x;
while(x < parenline.length) {
parenline[x] = line.charAt(x);
x++;
}
int l,r,i,morel,morer = 0;
while (i > parenline.length) {
if (parenline[i] == "(")
l++;
if (line.charAt(i) == ")")
r++;
i++;
}
if (l > r) {
morel = l-r;
System.out.println("There are " +morel+ " more left parentheses than right");
}
if (r > l) {
morer = r-l;
System.out.println("There are " +morer+ " more right parentheses then left");
}
if (r == l) {
System.out.println("The amount of left and right parentheses are even.");
}
}
}
定義「不工作」。在我看來,這個代碼將不能編譯,對於那些完全清楚的錯誤消息,我想你會得到解釋的原因,但它是誰也說不準 – EJP
可能的重複[如何在Java中比較字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Kon
@Kon我不知道我不這麼認爲。 –