0

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.");
    }

}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Chanell
  • 1
  • 1
  • What happens if you have a comment such as `// {{}`? – Jacob G. May 11 '18 at 22:43
  • or a char like `'}'`? – PM 77-1 May 11 '18 at 22:44
  • There is standard API to open a file as a Stream, which is very similar to the sorts of things a Scanner offers. Lot's of examples of how to do that such as https://stackoverflow.com/a/5868528/1531971 –  May 12 '18 at 01:34

1 Answers1

1

If you want to read from a File, change this

Scanner teclado = new Scanner(System.in);

to

Scanner teclado = new Scanner(new File("/somePath/someFile"));

And your Scanner will read from that File instead of from System.in; a more useful approach might be

Scanner teclado = new Scanner(new File(args[0]));

If you need to pass the file in as an argument.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249