简体   繁体   中英

IF statement isn't checking variable

Hello I'm trying to write a program that prints 3 numbers from a range being restricted to numbers from 0 to 99,but my If statement isn't double checking the variable.

    System.out.println("Please input a interger between 0-99:");
    int input1 = Input.nextInt();

        if (input1>99||input1<0){ 
            System.out.println("Outside range. Please enter an integer between 0-99");
             input1 = Input.nextInt();
        }        

        else if (input1>99||input1<0); 
                           System.out.println("Outside range program terminated.");

Two problems that I see:

Your second input (within the first IF) is not checked with the code shown. The else statement will NOT check the above mentioned problem because you've already passed that decision point when the original IF executed. The else is dependent on the IF's result. Here would be one way to fix.

Finally the 'else' needs brackets { }.

int input1 = 0;
Boolean myLoop = true;           //Sets up our loop flag
while(myLoop){                   //Loop while true
    System.out.println("Please enter an integer between 0-99");
    input1 = Input.nextInt();
    if (input1>99||input1<0){    //If input is outside the range send msg. 
       System.out.println("Data range error");
    }else{                       //If input is in range, end loop. 
       myLoop=false;
    }
 }        

This will continue to check until it get valid values.

While the others have given you a good code sample, I will like to point out where your code issue is. The code is not doing the double checking here because you have placed a semi-colon right at the end of the second if-else check, and the program will do nothing when it fulfill the if condition.I have replaced it with curly bracket. Try to compile and run it again.

   System.out.println("Please input a interger between 0-99:");
    int input1 = Input.nextInt();

        if (input1>99||input1<0){ 
            System.out.println("Outside range. Please enter an integer between 0-99");
             input1 = Input.nextInt();
        }        

        else if (input1>99||input1<0){
                           System.out.println("Outside range program terminated.");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM