我有一個Java問題,涉及閱讀一個文本文件,并檢查它是否正確地平衡了花括號,方括號和括號 - '{','}','[',']','('和') ”。
讀取文件沒有問題,但現在我應該使用名為DelimPos的數據成員來保存行和字符,只要在讀取文件時找到其中一個分隔符,然后將其放入Stack中即可。然后我應該通過堆棧并打印出任何錯誤(即不平衡的分隔符,如'{[}')。
每當我嘗試在主要方法中創建一個新的DelimPos d = new DelimPos(x, y)時,它給了我這個錯誤
No enclosing instance of type BalancedApp is accessible. Must qualify
the allocation with an enclosing instance of type BalancedApp (e.g.
x.new A() where x is an instance of BalancedApp).
我不確定在此計劃中使用DelimPos的最佳方式。
任何幫助,將不勝感激。
這是我的代碼:
import java.util.Stack;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.io.BufferedReader;
public class BalancedApp {
Stack s = new Stack();
public class DelimPos
{
private int linecnt;
private char ch;
public DelimPos(int lineCount, char character)
{
linecnt = lineCount;
ch = character;
}
public char getCharacter()
{
return ch;
}
public int getLineCount()
{
return linecnt;
}
}
public static void main(String args[]) {
int lineCount = 1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a file name: ");
String inputFile = sc.next();
try{
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
int text;
System.out.print(lineCount + ". ");
while((text = reader.read()) != -1)
{
char character = (char) text;
if(character == '\n')
{
System.out.print(character);
lineCount++;
System.out.print(lineCount + ". ");
}
else System.out.print(character);
DelimPos d = new DelimPos(lineCount, character);
}
}
catch(IOException e){
System.out.println("File Not Found");
}
}
}