简体   繁体   English

我不懂一行简单的代码

[英]I dont understand one simple line of code

Below is line: 下面是一行:

if (!seatNum[i]) 

I don't understand the purpose of this line.Code: 我不明白这行的目的。代码:

 if(economyClass<5) {
    for(int i=5;i<seatNum.length;i++) {
        if(!seatNum[i]) {
            seatNum[i]=true;
            System.out.println("Economy Class. Seat number: "+(i+1));
            economyClass++;
            break;
        }
    }
 }

It looks like seatNum is array of boolean, which mark if seat is taken. 看起来seatNum是布尔数组,如果已占用,则标记该数组。

if(!seatNum[i]) is if seat not taken, similar but shorter way of checking seatNum[i] == false if(!seatNum[i])是如果未占用座位,类似但更短的检查seatNum[i] == false

You are marking it as taken seatNum[i]=true; 您将其标记为seatNum[i]=true; and increase the economyClass number by economyClass++; 并按economyClass++;增加经济类编号economyClass++;

Supposing that seatNum[] is an array of booleans , that means: if the element at index i of seatNum is false, then proceed. 假设seatNum[]seatNum[]的数组,则意味着:如果seatNum索引iseatNum为false,则继续。

you can also read that as : if(seatNum[i] == false) 您也可以将其读取为: if(seatNum[i] == false)

seatNum[] must be a boolean array and !seatNum[i] expands to (seatNum[i]==false) which evaluates to true or false . seatNum[]必须为布尔数组, !seatNum[i]扩展为(seatNum[i]==false) ,其结果为truefalse So it is checking if seatNumber is not occupied and if not occupied alloting it. 因此,它正在检查seatNumber是否未被占用,以及是否未被分配。

In Java, the ! 在Java中,! is also called Boolean negation operator and what it does is inverting a boolean value: 也称为布尔取反运算符,它的作用是反转布尔值:

!true => false
!false => true

In order for the posted code to compile the seatNum array should contain booleans. 为了使发布的代码得以编译,seatNum数组应包含布尔值。

I can assume seatNum array as of boolean type as you have not mentioned the data type of array seatNum. 我可以假设seatNum数组为布尔型,因为您还没有提到数组seatNum的数据类型。 And if I am correct in my assumption, the content of array in the ith index can be true or false, if !true which is equals to false, the immediate line of the code sets true in the ith index. 如果我的假设是正确的,则ith索引中数组的内容可以为true或false,如果!true等于false,则代码的直接行将在ith索引中设置true。 In one line, ! 一行! is a logical not operator and not of true means false. 是逻辑上的非运算符,如果不是true则表示false。

Hope this helps you to explore more about operators in java 希望这可以帮助您探索有关Java运算符的更多信息

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

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