dimanche 17 juin 2018

Throwing exception for wrong data types?

in the case that I want to throw an exception when the wrong type of data type is entered, how can I do this with IllegalArgumentException?

if(row < 1) {
        row = 1;
    }
    if(row > 5) {
        row = 5;
    }
    if (row != int) {
        throw new IllegalArgumentException("Please enter appropriate integer.");
    }
    System.out.print("Specify red value (0-255): ");
    int red = console.nextInt();
    if(red < 0) {
        red = 0;
    }
    if(red > 255) {
        red = 255;
    }
    if (red != int){
        throw new IllegalArgumentException("Please enter appropriate integer.");
    }
    System.out.print("Specify green value (0-255): ");
    int green = console.nextInt();
    if(green < 0) {
        green = 0;
    } 
    if(green > 255) {
        green = 255;
    }
    if (green != int){
        throw new IllegalArgumentException("Please enter appropriate integer.");
    }
    System.out.print("Specify blue value (0-255): ");
    int blue = console.nextInt();
    if(blue < 0) {
        blue = 0;
    }
    if(blue > 255) {
        blue = 255;
    } 
    if (green != int){
        throw new IllegalArgumentException("Please enter appropriate integer.");
    }

My main problem is with the "!= int" part. I know for a fact that this is not right, but I am not sure what else to use. Using an else statement will not work either. If someone were to enter a double, string, or boolean input into the scanner instead of an integer, how could I throw an exception for this? I have to do this for an assignment, and they specifically said that I need to use a throw exception for this. Thanks everyone in advance!

Aucun commentaire:

Enregistrer un commentaire