简体   繁体   中英

else statements won't execute in an if else statement

For some reason, no matter what I do, every time I make an if else statement in my Java programs, it either only ever executes the if statement, or both the if and else statement.

import java.util.Scanner;

public class Week06_NelsonPimentel_Assignment {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] validnum;
        int i = 0;
        validnum = new int[5];

        System.out.println("Please enter a number between 50 and 100");

        while (i < validnum.length) {
            validnum[i] = input.nextInt();

            if (validnum[i] <= 101 || validnum[i] >= 49) {
                System.out.println("yes");
                i++;
            } else {
                System.out.println("no");
            }
        }

    }

}

if (validnum[i] <= 101 || validnum[i] >= 49) { will always evaluate to true , and so "yes" will be printed and i incremented, unless of course i is outside the bounds of the array.

Replace || with && ?

Also consider writing int[] validnum = new int[5]; rather than having two separate steps. That way, validnum is never in an uninitialised state which tends to result in stabler programs.

You have an endless loop in your code, when validnum[i] doesn't meet your condition you don't advance your loop index. Take i++; out of the if or replace your while loops with ( NOTE: You don't neet i++; if you are using for loop):

for (int i = 0; i < validnum.length; i++) {
        validnum[i] = input.nextInt();

        if (validnum[i] <= 101 || validnum[i] >= 49) {
            System.out.println("yes");
        } else {
            System.out.println("no");
        }
}

Why do you use the array? in the code you posted it looks like a waste of memory.

As per your business logic the if statement will always returns true.

My Observation: Please enter a number between 50 and 100.

validnum[i] = input.nextInt();
if (validnum[i] <= 101 || validnum[i] >= 49) {
}

Whether you are enter between 50 to 100 or less than 50 or greater than 100 the if statement will always satisfied either one of the below condition

validnum[i] <= 101 
validnum[i] >= 49

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