Pick only numbers from a String (Tokenizer)

Asked

Viewed 290 times

0

Hello, I’m doing a project with stack and queue, and I’m in a part I need to pick up the operator and put in a pile and the number in a queue.

However this part of taking the number is not working, someone has a light to work, because what I used the net is not working. Note: not giving 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]+");   
}    

}

1 answer

2


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

The right thing would be this way:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.