if表达式算法错误



我想传入x, yz的值,并让它们通过算法。但是我得到了一个错误。我想我在做违法的事,但我不确定。

错误是这样的:

if((istrue1)||(istrue2&&istrue3)){
            ;
}

我的完整代码是:

package com.company;
public class Main {
    public static void main(int x, int y, int z) {
        boolean istrue1, istrue2, istrue3;
        if((istrue1=(x >=1 && x<=31)) || (istrue2=(y>=1 && y<=31)) || (istrue3=(z >= 1 && z<=31)));{
            if((istrue1)||(istrue2&&istrue3)){
                ;
            }
        }
    }
}

代码中(至少)有两个问题(但我怀疑只有第二个问题是您这里的问题的一部分。

第一个问题是你的外部if语句在末尾有一个';'。因此,虽然从缩进来看,您嵌套了if语句,但实际上并没有。

第二个问题比较微妙,它与if语句短路了对其条件的求值有关。

你有

if 
(
    a = first_condition ||
    b = second_condition ||
    c = third_condition
)
{
   ...do stuff
}

这是合法的语法,但是如果first_condition为真,那么编译器知道整个if条件为真,所以它不需要计算第二个两个子句。这意味着,如果first_condition为真,那么'b'和'c'都不会被赋值。

我的建议是重做代码

boolean a = first_condition
boolean b = second_condition
boolean c = third_condition
if (a || b || c)
{
   //do stuff
}

你的方法有很多错误,几乎无法挽回:

并详细解释如何以及为什么所有的问题将是一个完整的类,并且超出了StackOverflow的范围,因为它将是一个太宽泛的主题。

也就是说,你确实做了尝试,所以这里是如何真正做你正在尝试做的一部分。希望这将澄清如何使用boolean逻辑。

/* This removes the duplication of logic and remediates 
   the *line noise* looking code that duplication introduced.
*/
public static boolean inRangeInclusive(final int low, final int value, final int hi)
{
    return low <= value && value <= hi;
}
public static void main(final String[] args)
{
    final int x = Integer.parseInt(args[0]);
    final int y = Integer.parseInt(args[1]);
    final int z = Integer.parseInt(args[2]);
    if ( inRangeInclusive(1,x,31) || inRangeInclusive(1,y,31) || inRangeInclusive(1,z,31)) ;
    {
        /* whatever you want to happen if any of those things match goes here */
    }
}
    花时间学习如何使所有的方法参数final和所有的local引用final,它将节省你比你想象的更多的时间!
  1. 如果写的东西看起来像line noise或猫走过键盘,那么它可能是错误的。即使它似乎产生了你想要的行为。

最新更新