samedi 22 juillet 2017

Defining a variable in IF statement (Java)

I'm currently learning Java and as part of it I'm trying to make a random number generator.

The project's still at it's early stage but when I was making the error checker component, I faced some issue which I've always been wondering why it doesn't work this way.

Following is the error checker, where it takes in the numberAmount (Amount of random numbers requested by the user) and randomDigit(Largest digits of the random numbers).

I want to make it so it flags when the amount or the digit is too high which could make the app crash.

The following is the code.

public static boolean errorCheck(int numberAmount, int numberDigit){

    //int checkAmount = 0;
    //int checkDigits = 0;

    if (numberAmount > 15){
        System.out.println("We can't generate that many numbers!");
        int checkAmount = 1;
    } else if (numberAmount < 0){
        System.out.println("We can't generate negative amount of numbers!");
        int checkAmount = 1;
    } else if (numberAmount == 0) {
        System.out.println("Zero numbers requested");
        int checkAmount = 1;
    } else {
        int checkAmount = 0;
    }

    if (numberDigit > 15){
        System.out.println("We can't generate that many numbers!");
        int checkDigit = 1;
    } else if (numberDigit < 0){
        System.out.println("We can't generate negative amount of numbers!");
        int checkDigit = 1;
    } else if (numberDigit == 0) {
        System.out.println("Zero numbers requested");
        int checkDigit = 1;
    } else {
        int checkDigit = 0;
    }


    if (checkAmount == 1 || checkDigit == 1){
        return true;
    } else {
        return false;
    }
}

When I don't insert the int checkAmount = 0; and int checkDigits = 0;, the last if statement errors due to no referable variable as such. However if I do include it all the check variables in first and second if statement errors for pre-existing local variable.

I've tried some fixes and read online but I still don't really understand why I can't define or override variables inside if statement.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire