[英]Resetting a Boolean variable in Java
我目前正在編寫一個程序,一旦前一個對象滿足布爾變量返回 true 的條件,它就會生成一個新對象。 我遇到的問題是我正在處理多種不同的形狀。 該程序可以完美運行,直到出現第二種形狀。 此時它有兩個形狀滿足它們的布爾值 isDone() 條件。 有沒有一種簡單的方法可以將布爾變量返回為 false/它的默認條件?
代碼:
if (baserectangle.isDone()) {
int meowchoice = (int) Math.round(2 * Math.random());
if (meowchoice < 1) {
baserectangle = (new Rectangle(10, 25, position, m, n));
scene1.add(baserectangle);
}
if (meowchoice >= 1) {
basesquare = (new Square(10, 25, position, m, n));
scene1.add(basesquare);
}}
else if (basesquare.isDone()) {
int meowchoice2 = (int) Math.round(2 * Math.random());
if (meowchoice2 < 1) {
baserectangle = (new Rectangle(10, 25, position, m, n));
scene1.add(baserectangle);
}
if (meowchoice2 >= 1) {
basesquare = (new Square(10, 25, position, m, n));
scene1.add(basesquare);
}
}
即程序以 baserectangle 或 basesquare 開始,然后當該形狀滿足其 isDone 條件時,隨機生成一個新的 baserectangle 或 basesquare。 問題在於,一旦 baserectangle 和 basesquare 都存在,它一次會不斷生成多個形狀。
isDone() 實現:
public boolean isDone() {
if (this.y < 2) {
return true;
}
if (i > 0 && position [i-1][j] != 0) {
return true;
}
else return false;
}
其中 this.y 是平面上形狀的 y 坐標,i 和 j 是對象在數組中的位置。
您可以在類中放置另一個變量,例如alreadyDone
並使用它來決定是否必須生成其他形狀,例如:
public boolean isDone() {
if (this.y < 2) {
alreadyDone = true;
return true;
}
if (i > 0 && position [i-1][j] != 0) {
alreadyDone = true;
return true;
}
else return false;
}
並在檢查期間:
if (!baserectangle.alreadyDone && baserectangle.isDone()) { ...
請記住,這只是一個例子,我相信有更好的方法來做到這一點
該程序可以完美運行,直到出現第二種形狀。 此時它有兩個形狀滿足它們的布爾值 isDone() 條件
當然,你有兩種形狀。 問題可能在於該事實,你永遠只檢查一個是以做if-else if
組合。
您可能需要檢查任一形狀是否使用單獨的 if 語句完成。
// Rectangle is done
if (baserectangle.isDone()) {
int meowchoice = (int) Math.round(2 * Math.random());
if (meowchoice < 1) {
baserectangle = (new Rectangle(10, 25, position, m, n));
scene1.add(baserectangle);
}
else if (meowchoice >= 1) {
basesquare = (new Square(10, 25, position, m, n));
scene1.add(basesquare);
}
}
// Square is done
if (basesquare.isDone()) {
int meowchoice2 = (int) Math.round(2 * Math.random());
if (meowchoice2 < 1) {
baserectangle = (new Rectangle(10, 25, position, m, n));
scene1.add(baserectangle);
}
else if (meowchoice2 >= 1) {
basesquare = (new Square(10, 25, position, m, n));
scene1.add(basesquare);
}
}
但是,這兩個if語句的內容是完全一樣的,所以你可以這樣做
// Rectangle or Square are done
if (baserectangle.isDone() || basesquare.isDone()) {
int meowchoice = (int) Math.round(2 * Math.random());
if (meowchoice < 1) {
baserectangle = (new Rectangle(10, 25, position, m, n));
scene1.add(baserectangle);
}
else if (meowchoice >= 1) {
basesquare = (new Square(10, 25, position, m, n));
scene1.add(basesquare);
}
}
如果你想縮短isDone
方法......
public boolean isDone() {
return (this.y < 2) || (i > 0 && position [i-1][j] != 0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.