Check if String is number, if not, return error to user

3

I'm doing a Java code using JOptionPane, and in it, I created an InputDialog that returns the value "1", "2" or "3" entered by the user to a String variable called "return". That done, I need to convert it to int, using Integer.parseInt() . However, if the user types something other than number would give an error in execution at the time of converting to integer , and I do not want this.

String retorno;
int op;

retorno = JOptionPane.showInputDialog(null, " 1- Criar uma conta \n 2- Acessar uma conta \n 3- Sair");
op = Integer.parseInt(retorno); //se não for número, da erro =/

How to construct the code for when the user enters a value, make sure it is number, and if not, to return an error to the user instead of sticking and stop execution ?

    
asked by anonymous 30.11.2015 / 17:55

4 answers

7

Since it is only 3 values, you can make a switch-case for each of the options. It's less expensive than throwing an exception.

Code:

import javax.swing.JOptionPane;

public class Teste {
    public static void main(String[] args) {
        String retorno = JOptionPane.showInputDialog(null, " 1- Criar uma conta \n 2- Acessar uma conta \n 3- Sair");
        int op=0;
        switch (retorno) {
        case "1":
            op=1;
            break;
        case "2":
            op=2;
            break;
        case "3":
            op=3;
            break;
        default:
            break;
        }
        System.out.println(op);
    }
}
    
30.11.2015 / 18:05
5

There are several ways to do this, how you're going to do depends a little on taste and also the complexity of your application, but come on.

If it is a small application and you only want to validate if the user input is equal to 1 , 2 or 3 3, a switch-case validating if the input is one of these values.

retorno = JOptionPane.showInputDialog(null, " 1- Criar uma conta \n 2- Acessar uma conta \n 3- Sair");
switch (retorno)
{
    case "1":
        //Operação 1
    case "2":
        //Operação 2
    case "3":
        //Operação 3
    default:
        JOptionPane.showMessageDialog(null, "Entrada inválida", "Alerta", JOptionPane.ERROR_MESSAGE);
}
    
30.11.2015 / 18:05
4

One of the ways would be to wrap with try/catch , capturing a NumberFormarException . If you throw the exception, you return the error in catch .

try{
op = Integer.parseInt(retorno);

}catch(NumberFormatException ex){

JOptionPane.showMessageDialog(null,"opção inválida","Alerta",JOptionPane.ERROR_MESSAGE);
}

Remembering that where null you can reference the Jframe of your screen.

References:

link

link

    
30.11.2015 / 18:04
4

Alternatively you can create a method that checks the characters to see if it is a String or Integer .

Example:

public static boolean validarString(String texto) {
        String valor = texto;
        boolean valido = true;

        for (int i = 0; i < valor.length(); i++) {
            Character caractere = valor.charAt(i);
            if (!Character.isDigit(caractere)) {
                //É String
                valido = false;
            }
        }
        //É numero
        return valido == true;
    }

Then on the Main:

public static void main(String[] args) {
         String retorno = JOptionPane.showInputDialog(null, " 1- Criar uma conta \n 2- Acessar uma conta \n 3- Sair");
         if(validarString(retorno)){
             System.out.println("Numero");
         }else{
             System.err.println("String");
         }
    }
    
30.11.2015 / 18:19