I have to make a program that reads a .java file, and check if the number of curly braces opened are the same as the closed, it has to be with stacks. This is what I have done, but cleary I'm using the Scanner
and introducing there the program, and it doesn't have to be like that, it has to be with a .java file.
public class Llaves1 {
public static int numPila;
private int t = -1;
private char[] pila; Llaves1(int size){
this.pila = new char[size];
numPila++;
}
public int size(){
return (t+1);
}
public boolean isEmpty(){
if(t==-1)
return true;
else
return false;
}
public void push(char x){
if(this.size()== this.pila.length)
{
System.out.println("Pile is already full.");
}
else {
this.pila[++t]=x;
}
}
public char pop(){
if(isEmpty()){
System.out.println("Empty Pile.");
}
return pila[t--];
}
public char top(){
if(isEmpty()){
System.out.println("Empty pile.");
}
return pila[t];
}
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
String cadena= teclado.nextLine();
Llaves1 a= new Llaves1(cadena.length());
for(int i=0; i<cadena.length();i++){
char temp = cadena.charAt(i);
a.push(temp);
}
if(a.isEmpty())
System.out.println("Is empty.");
int numC=0;
int numA=0;
for(int i=0; i<cadena.length(); i++){
if(a.top()=='}')
numC++;
if(a.top()=='{')
numA++;
a.pop();
}
if(numA!=numC)
System.out.println("You have to close curly braces");
else
System.out.println("all curly braces have been closed.");
}
}