简体   繁体   中英

How can I correct this int to boolean error?

Sorry I am having a mental block, can anyone see why I get the 'cannot convert from int to boolean' error message. Much appreciated

public static void main (String[]args) {
  int max=10;
  int sum=0;
  int count=0;
  for(int counter=0;counter=max-4;counter++) {
    sum=max-4;
    count=max-3;
    for(sum=3;sum<5;sum++) {
      if(count==0 && max>0){
        System.out.println("Hello");
      } else if (count<4) {
        System.out.println("Go for it");
      } else {
        System.out.println("OK");
      } 
    }
  }
  sum=sum+count;
  System.out.println("Total = "+sum);
  System.out.println("Max = "+count);
}

I feel like I have checked using the '==' for the if condition.

= is assignment, you need a comparison in the second term of your loop.

for(int counter=0;counter=max-4;counter++) {

should be

for (int counter = 0; counter < max - 4; counter++) {

(white space added, but note < is a comparison... perhaps you wanted <= ).

In case of Java, the syntax of for loop is

for(initialization; Boolean_expression; update) {
    // Statements
}

1) The initialization part executes only once when the flow enters the for loop for the first time

2) Next, the boolean expression is resolved according to the condition

3) Then next the update statement is resolved and after execution of the body of the for loop again the flow goes to the boolean expression and then update statement and the flow goes on.

So, In your program instead of a boolean expression, you have used an assignment operator which turns out to be 6 which is not 0 or 1. Boolean expression are true = 1 and false = 0 . Hence the integer 6 cannot be converted to boolean. So, you can go with counter < max-4

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