Exceptions with a string and its values

0

I should be able to make use of the exceptions asking for data by console and that the string you enter should analyze me if there is any character that is not alphanumeric.

As soon as I find a non-alphanumeric character that stops.

Code:

import java.io.IOException;
import java.util.Scanner;

public class ActivitatEx3a {


    public static void main(String[] args) throws IOException, Exception {
        boolean var = false;
        System.out.println("Entra una cadena: ");
        String entradaTeclado = "";
        @SuppressWarnings("resource")
        Scanner entradaEscaner = new Scanner (System.in);
        entradaTeclado = entradaEscaner.nextLine (); 
            for(int i = 0; i < entradaTeclado.length(); ++i) {
                char caracter = entradaTeclado.charAt(i);
                if(!Character.isLetterOrDigit(caracter)) {
                        System.out.println("no alfa");
                }
            }       
    }
}
    
asked by Oriol 13.12.2017 в 19:51
source

1 answer

0

I do not see why to avoid exceptions. It can be expensive, but it depends on the program. In the case of the one that shows, I do not see anything expensive. But I respect and understand the comment.

In the case, of wanting to use exception in your example, I would separate the validation of the reading, in a valid method (String entry), and I would throw IllegalArgumentException as it would be the logic to use.

public static void valida(String entrada) { 
    if (entrada == null) {
        throw new IllegalArgumentException("entrada nula");
    }
     for(int i = 0; i < entradaTeclado.length(); ++i) {
            char caracter = entradaTeclado.charAt(i);
            if(!Character.isLetterOrDigit(caracter)) {
               throw new IllegalArgumentException("carater ilegal:"+caracter);
            }
        }
}      

Then I would change your main method to something like this:

public static void main(String[] args) throws IOException, Exception {
    boolean var = false;
    System.out.println("Entra una cadena: ");
    String entradaTeclado = "";
    @SuppressWarnings("resource")
    Scanner entradaEscaner = new Scanner (System.in);
    entradaTeclado = entradaEscaner.nextLine (); 
    try {
        valida(entradaTeclado);
        System.out.println("entrada correcta:"+entradaTeclado);
    }
    catch (IllegalArgumentException e) {
        System.out.println("error en entrada:"+e.getMessage();
    }       
}

I hope this example serves you. Greetings!

    
answered by 16.12.2017 в 05:33