I have a Java problem that involves reading a text file and check that it has properly balanced curly braces, square brackets, and parentheses - '{', '}', '[', ']', '(', and ')'.
I have no problem reading the file, but now I am supposed to use a data member called DelimPos to hold onto the line and character whenever I find one of the delimiters while reading the file and then put it in a Stack<DelimPos>
. I am then supposed to go through the stack and print out any errors (ie. unbalanced delimiters like '{ [ }').
Whenever I try to make a new DelimPos d = new DelimPos(x, y)
in the main method, it gave me this error
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).
I am unsure what the best way would be to use DelimPos in this program.
Any help would be appreciated.
Here is my code:
import java.util.Stack;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.io.BufferedReader;
public class BalancedApp {
Stack<DelimPos> s = new Stack<DelimPos>();
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");
}
}
}