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

Asked

Viewed 3,199 times

3

I’m making a code in Java using Joptionpane, and in it, I created an Inputdialog that returns the value "1","2" or "3" typed by the user to a String variable called "return". Once this is done, I need to convert it to int, using the Integer.parseInt(). However, if the user type something other than number would give error in running when converting to integer, and I don’t want it.

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 build code for when user enters a value, make sure it is number, and if not, return an error to the user instead of giving up and stop the execution?

  • 1

    You only want to accept the values 1, 2 or 3?

  • @jbueno yes! Only these values.

  • http://www.guj.com.br/java/66577-como-verifiar-se-a-string-e-letra-ou-numero

  • You can only choose one answer like the "correct" ;-) PS: Feel free to choose the one you found the most suitable for your situation.

4 answers

8


As it comes to only 3 values, you can make one switch-case for each of the options. It is less costly than making 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);
    }
}
  • 2

    I can barely see your movements

  • 1

    worked, thanks!

5

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

If it is a small application and you only intend to validate if the user input is equal to 1, 2 or 3 better make a switch-case validating whether 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);
}
  • 1

    worked, thanks!

4

One of the ways would be to engage with try/catch, capturing a NumberFormarException. If you launch 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 where you are null you can reference the Jframe of your screen.

References:

http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html

https://stackoverflow.com/a/1102916/5524514

  • 1

    It worked! Thank you very much! ^^

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

Browser other questions tagged

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