1
我正在製作一個程序來檢查大括號在另一個程序中是否平衡,並且我在靜態與非靜態變量方面遇到了問題。它說我無法從靜態上下文中引用我的非靜態堆棧,但我正在閱讀文件,所以我必須更改堆棧。有什麼建議麼?謝謝!靜態與非靜態堆棧
public static void main(String[] args)
{
readFile();
if(isBalanced() == true)
System.out.println("program is balanced");
else
System.out.println("program is not balanced");
}
private static void readFile()
{
try
{
Scanner fin = new Scanner(new File("test.txt"));
while(fin.hasNext())
{
s.add(fin.nextLine());
System.out.println("");
}
}catch(IOException ex)
{
System.out.println("File Not Found");
}
}
public static boolean isBalanced()
{
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i) == LEFT_PARENT)
stack.push(LEFT_PARENT);
else if(s.charAt(i) == LEFT_BRACE)
stack.push(LEFT_BRACE);
else if(s.charAt(i) == LEFT_BRACKET)
stack.push(LEFT_BRACKET);
else if(s.charAt(i) == LEFT_POINT)
stack.push(LEFT_POINT);
else if(s.charAt(i) == RIGHT_PARENT)
{
if(stack.isEmpty())
return false;
if(stack.pop() != LEFT_PARENT)
return false;
}
else if(s.charAt(i) == RIGHT_BRACE)
{
if(stack.isEmpty())
return false;
if(stack.pop() != LEFT_BRACE)
return false;
}
else if(s.charAt(i) == RIGHT_BRACKET)
{
if(stack.isEmpty())
return false;
if(stack.pop() != LEFT_BRACKET)
return false;
}
else if(s.charAt(i) == RIGHT_POINT)
{
if(stack.isEmpty())
return false;
if(stack.pop() != LEFT_POINT)
return false;
}
}
return stack.isEmpty();
}
}