Task:
My implementation:
public class Main {
public static void main(String[] args) {
String fileName = "Brackets.txt";
Path filein = Paths.get(fileName);
ParentStack s = new ParentStack();
if (!Files.exists(filein) ||
!Files.isReadable(filein) ||
Files.isDirectory(filein)) {
System.err.println("Invalid input file !!!");
System.exit(1);
}
try (BufferedReader br = Files.newBufferedReader(filein);){
String line;
char[] arrLineChar = null;
char expected;
int lineNumber = 0;
boolean error = false;
read: while ( (line = br.readLine()) != null) {
int charNumber = 0;
lineNumber++;
arrLineChar = line.toCharArray();
for (char lineChar : arrLineChar) {
charNumber++;
if(lineChar == '(' || lineChar == '{' || lineChar == '['){
s.push(lineChar);
}
if(lineChar == ')'){
if((expected = s.pop()) == lineChar-1){
}else{
System.out.println(line);
for (int j = 0; j < charNumber-1; j++) {
System.out.print(" ");
}
if(expected == '(')expected +=1;
else expected+=2;
System.out.println("^");
System.out.println("ERROR in line " + lineNumber + ". " + lineChar
+ " found, but "+ (expected) + " expected.");
error = true;
break read;
}
}
if(lineChar == '}'){
if((expected = s.pop()) == lineChar-2){
}else{
System.out.println(line);
for (int j = 0; j < charNumber-1; j++) {
System.out.print(" ");
}
if(expected == '(')expected +=1;
else expected+=2;
System.out.println("^");
System.out.println("ERROR in line " + lineNumber + ". " + lineChar
+ " found, but "+ (expected) + " expected.");
error = true;
break read;
}
}
if(lineChar == ']'){
if((expected = s.pop()) == lineChar-2){
}else{
System.out.println(line);
for (int j = 0; j < charNumber-1; j++) {
System.out.print(" ");
}
if(expected == '(')expected +=1;
else expected+=2;
System.out.println("^");
System.out.println("ERROR in line " + lineNumber + ". " + lineChar
+ " found, but "+ (expected) + " expected.");
error = true;
break read;
}
}
}
}
if(error == false)System.out.println("OK");
} catch(IOException e) {
System.err.println("IOException");
System.exit(1);
}catch(ArithmeticException e) {
System.err.println("ArithmeticException");
System.exit(1);
}catch(NumberFormatException e) {
System.err.println("NumberFormatException");
System.exit(1);
}catch(Exception e){
System.err.println("Error");
}
}
}
public class ParentStack {
private Node top;
public void push(char p){
top = new Node(p, top);
}
public char pop(){
char buf = top.getVal();
top = top.getNext();
return buf;
}
public boolean empty(){
return top == null;
}
}
public class Node {
private char val;
private Node next;
public char getVal() {
return val;
}
public Node getNext() {
return next;
}
public Node(char val, Node next){
this.val=val;
this.next=next;
}
}
Bracets.txt
Warsaw(){
London[xxxx} (
Madrid Paris)}
Berlin
I realise that this is awful but it's what i can come up right now that is actually working. I tried other way but my knowledge is not enough to do it. So what can i do better so far?