简体   繁体   English

else语句不会在if else语句中执行

[英]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. 由于某种原因,无论我做什么,每次我在Java程序中创建if else语句时,它要么只执行if语句,要么执行if和else语句。

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. if (validnum[i] <= 101 || validnum[i] >= 49) {将始终为true ,因此将打印“ yes”并递增i ,除非i当然不在数组范围之内。

Replace || 替换|| with && ? &&

Also consider writing int[] validnum = new int[5]; 还可以考虑编写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. 这样, validnum永远不会处于未初始化状态,这会导致程序更稳定。

You have an endless loop in your code, when validnum[i] doesn't meet your condition you don't advance your loop index. 您的代码中有一个无限循环 ,当validnum[i]不满足您的条件时,您不会推进循环索引。 Take i++; i++; out of the if or replace your while loops with ( NOTE: You don't neet i++; if you are using for loop): 出来的if或更换while与循环( 注:你不NEET i++;如果您使用for循环):

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. 根据您的业务逻辑,if语句将始终返回true。

My Observation: Please enter a number between 50 and 100. 我的观察:请输入50到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 无论您输入的是50到100之间还是小于50或大于100之间,if语句将始终满足以下条件之一

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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