![](/img/trans.png)
[英]C#: How to check if all the elements in an array of boolean variables are of the same value (All true or All false)?
[英]How to check if a specific index in a boolean array is true is C#
我必须创建一个简单的 windows 表单应用程序,将客户分配到 First Class 1-5 或 Economy Class 6-10 中的座位。 我必须使用一维 boolean 数组。 我不知道如何检查特定索引是否已设为True 。 如果数组为真,它要么继续前进,要么创建一个消息框。 我只需要有关如何检查其是否真实的帮助。
for (int i = 5; i < 9; i++)<br>
{
assignedSeat[i] = true;
if (assignedSeat[9] == true)
{
MessageBox.Show("You chose Economy Class", "Economy Class",
MessageBoxButtons.OK);
}
else
{
DialogResult g = MessageBox.Show("Unfortunately, Economy class is full. Next flight in 3 hours",
"Oh No", MessageBoxButtons.OKCancel);
if (g == DialogResult.OK)
{
TxtClassChoice.Clear();
}
else
{
Close();
}
}
}
我认为这里的混乱是for循环。
for (int i = 5; i < 9; i++)
9 - 5 = 4。
你在这里只检查 4 个座位。 座位 6 至 9。
if (assignedSeat[9] == true)
将始终为假。 那是因为i < 9
条件。
知道这一点, assignedSeat[i] = true;
永远不会运行assignedSeat[9] = true;
.
boolean 的默认值为 false。
如果要检查座位 6 到 10,请将i < 9
更改为i < 10
:
for (int i = 5; i < 10; i++)
我不知道如何检查特定索引是否已设为 True。
if (assignedSeat[9] == true)
非常好。 它可以缩短为if (assignedSeat[9])
但这只是偏好。
您的代码中至少有两个错误。 首先,您需要遍历所有座位以一一检查它们是否空闲。 这意味着包括从 5 到 9 的循环(索引 5 用于座位 6,因为 arrays 是从零开始的)。 第二个错误是每个席位的分配为真。 当然,这应该只在您找到一个空闲座位而不是每个循环时才进行一次。
但是,在修复这些错误之后,您可以做更多的事情。 尝试将检查空闲座位的逻辑与显示消息的逻辑分开。
// Cycle from 5 to 9 (seats 6-10)
int seatNum = 5;
while(seatNum < 10)
{
// If the seat is free stop the cycle
if(!assignedSeat[seatNum])
break;
seatNum++;
}
// If we exit the loop after reaching the last seat then we don't have free seats
if(i == 10)
MessageBox.Show("Unfortunately, Economy class is full.....");
else
{
assignedSeat[seatNum] = true;
MessageBox("You chose Economy Class, assigned seat is " + seatNum+1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.