简体   繁体   中英

How do you put a if, else statement within a for statement

How do you put an if...else statement within a for statement?

This is the code:

// This is within a actionListener. When ever I press a button, this happens.
for (int i = 0; i < booleanVariable.length; i++) {
    //length is 8
    System.out.println("booleanVariable is" + booelanVariable[i]);
    if (booleanVariable[i] = true) {
        booleanVariable[i] = false;
        System.out.println("booleanVariable was true")
        break;
    } else {
        System.out.println(" booleanVariable is false");
    }
}

This is the output over 3 presses:

booleanVariable is true
booleanVariable was true
//correct    


booleanVariable is false
booleanVariable was true
//incorrect.    

booleanVariable is false
booleanVariable was true
//incorrect

This means that, for some reason, even if booleanVariable is false, the output says is true, which is false.

What I've found:

  • Without the break; statement, the program goes around the for all 8 times and outputs exactly the same as without a break , only incorrect values another 5 times.

What I've tried:

  • Changing the if from true to false (out of desperation)
  • If within a While within a For
  • else, else if
  • case switch

Normally, I'd just use a switch, but I'm using booleans, and booleans dont work is switches.

If someone knows the answer, I'd be forever grateful. Thanks.

Your problem may be in this line:

if (booleanVariable[i] = true) {

Boolean comparisons should use == , unless you are intending to set the value to true. In any event, this line will always evaluate to true.

Note also that you never really need to compare to true , you can simply say something like:

if (booleanVariable[i]) {

since if the value is true, the code block will be entered, and if it is false, it will proceed to the else case.

Change your

if (booleanVariable[i] = true) {

to

if (booleanVariable[i] == true) {

You need to use == operator for comparison. One = sets the value to true which returns always true. You can also change it to

if (booleanVariable[i]) {

You have to use == to compare the values. Yu use the = that asigns the value true to the variable so it will always be true

if (booleanVariable[i] == true)

There's an error in the if statement --

You are assigning true to the variable, that's why it's outputting true each time. it needs to be == (equals) not = (assign).

if (booleanVariable[i])代替if (booleanVariable[i] = true) .... =是赋值运算符...您也可以使用==代替

You should change if (booleanVariable[i] = true) as if (booleanVariable[i] == true). need '==' instead of '='.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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