写错的布尔方法?

时间:2015-10-25 11:28:17

标签: if-statement boolean operators

我有布尔方法的这个问题,描述在评论中,但我不明白:为什么这是"假"在这里括号之后?以及如何使用if语句查看条件在返回时是对还是错?我无法修改任何其他内容,但这些括号。我完全糊涂了。我理解下面的代码,首先我有条件(a&& b)? "然后是什么"但在第一个代码中,我没有得到它。这是我的代码:

public class Aufgabe5 {

    // returns true if (and only if) both x and y are in the range from 1 to 20 (including 1 and 20)
    // and x is larger than y.
    private static boolean inRangeAndOrdered(int x, int y) {
        return (false /* TODO: modify this expression */);
    }

    // returns 1 if both a and b are true, 0 if a differs from b, and -1 if both a and b are false
    private static int wiredLogic(boolean a, boolean b) {
        return (a && b ? (-1 /* TODO: modify this expression */) : (-1 /* TODO: modify this expression */)) +
               (a || b ? (-1 /* TODO: modify this expression */) : (-1/* TODO: modify this expression */));
    }

1 个答案:

答案 0 :(得分:0)

我无法回答为什么false在括号后面,因为我不知道你为什么会在那里?可能是你需要的一个奇怪的要求。听起来你出于某种原因需要false。但是,没有它,这种方法更容易编写,更容易理解。

以下方法将在评论中实现您的要求(同时使用false)。

// returns true if (and only if) both x and y are in the range from 1 to 20 (including 1 and 20)
// and x is larger than y.
private static boolean inRangeAndOrdered(int x, int y)
{
    return (false == !(x >= 1 && x <= 20 && y >= 1 && y <= 20));
}

此退货声明正在做什么:

首先,如果x大于或等于1且小于或等于20,x >= 1 && x <= 20将等同于true

其次,如果y大于或等于1且小于或等于20,则y >= 1 && y <= 20将等同于true

然后使用&&合并两个语句的结果并用括号括起来。如果x和y都大于或等于1且小于或等于20,则整个括号内的语句等于true

在括号前添加“not”关键字!将反转布尔值。因此,如果括号内的陈述等同于真,那么它将被颠倒为假。

示例:

true == !true = falsefalse == !false = false

return语句比较括号中的false == !({statement})的反转等值:

  1. 如果{statement} = true,则反转为false,false等于false,返回true。
  2. 如果{statement} = false,则反转为true,true不等于false,返回false。
  3. 此返回主要使用if statement。它也可以读作如下,但我上面提到的代码是简短形式:

    if (false == !(x >= 1 && x <= 20 && y >= 1 && y <= 20))
        return true;
    else
        return false;
    

    以下方法达到了第二种方法评论中的要求:

    // returns 1 if both a and b are true, 0 if a differs from b, and -1 if both a and b are false
    private static int wiredLogic(boolean a, boolean b)
    {
        return (a && b ? 1 : (a == b ? -1 : 0));
    }
    

    此返回声明正在进行三项检查以满足要求:

    1. 如果a和b的组合为真,则返回1.
    2. 如果a和b的组合不为真且a等于b则a和b都为假,则返回-1。
    3. 如果a和b的组合不为真且a不等于b则a为假且b为真或b为假且a为真,则返回0.
相关问题