Pick up only numbers from a String (Tokenizer)

0
Hello, I'm doing a project with stack and queue, and I'm in a part that I need to get the operator and put in a stack and the number in a queue.

But it's not working this part to get the number, someone has a light to work, because what I used the net is not working. Note: this is not an error!

public class JavaApplication1 {

 /**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here       

    Scanner input = new Scanner(System.in);

    String exp;

    Fila fila = new Fila();
    Pilha pilha = new Pilha();

    int valor;



    try {
        System.out.println("Digite um texto.");

        exp = input.next();


        StringTokenizer st = new StringTokenizer(exp, "+-*/^()", true);
        while (st.hasMoreTokens()) {

            if (campoNumerico(st.nextToken())) {

                try {
                    valor = Integer.parseInt(st.toString());
                    fila.insere(st);
                } catch (NumberFormatException e) {
                    System.out.println("Numero com formato errado!");
                }

            } else {

                pilha.empilhar(st.nextToken());

            }                 

         //   String delimitador;

         //   Float.parseFloat(st.nextToken());
        } 

        fila.mostrar();

    } catch(Exception erro) {

    }
     System.out.println("Valores pilha: " + pilha);                    

}

private static boolean campoNumerico(String campo){           
        return campo.matches("[0-9]+");   
}    

}

    
asked by anonymous 16.03.2017 / 23:51

1 answer

2

There are two errors, the first is that you are consuming token during if and are not storing their value. The second is that you are passing as an argument to the method Integer.parseInt the value returned by method toString of class StringTokenizer instead of token.

The correct way would be this:

StringTokenizer st = new StringTokenizer(exp, "+-*/^()", true);
while (st.hasMoreTokens()) {
    String token = st.nextToken();
    if (campoNumerico(token)) {
        try {
            fila.insere(Integer.parseInt(token));
        } catch (NumberFormatException e) {
            System.out.println("Numero com formato errado!");
        }
    } else {
        pilha.empilhar(token);
    }                 
}
    
17.03.2017 / 00:36