Error in for loop: "incompatible types: int can not be converted to boolean"

3

I am new to StackOverflow and also programming in Java. I am going through exercises that I did in pseudocodigo to Java, and I find an error that I can not solve in the for loop.

The idea of the exercise is to create a vector that contains free and occupied cinema seats, then go through the vector and return the number of seats occupied.

I transcribe the code:

public class butacasdecine {
public static void main (String[] args)
{
    int [] butacas = {1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1};
    int contador = 0;


    for (int i=0; i=11; i++)
    {
       if (butacas[i]==1);
       contador++;          
    }
  System.out.println("Butacas ocupadas: " +contador);
} 

The error appears in the line of'for (int i = 0 ... 'and says verbatim: "incompatible types: int can not be converted to boolean

The assigned value is never used "

Thanks for the help !!

    
asked by Die Duro 12.06.2017 в 22:40
source

3 answers

1

The second parameter of the loop must be a condition. Therefore, right now you are doing an assignment and that is why you are giving an error telling you that I expected a Boolean value ( true or false , result of a condition).

You should use the symbols > , < , <= , >= or == .

Example:

for (int i=0; i<=11; i++)

In this case, for example, it would go through all the numbers between 0 and 11, both inclusive (since it has the = ).

    
answered by 12.06.2017 / 22:41
source
1

You must modify the boolean condition of your for: your code should look like this:

public class butacasdecine {
public static void main (String[] args)
{
    int [] butacas = {1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1};
    int contador = 0;


    for (int i=0; i<=11; i++)
    {
       if (butacas[i]==1);
       contador++;          
    }
  System.out.println("Butacas ocupadas: " +contador);
} 
    
answered by 12.06.2017 в 23:06
1

You can use a forEach to traverse the array with the seats and so go comparing in each iteration if the value is equal to 1, increasing the counter if this condition is met, I leave the code, anyway it would be good practice Testing with Junit helps too much when it comes to programming algorithms like these.

@Test
public void validarButacasTest() {

    int[] butacas = { 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1 };
    int contador = 0;

    for (int i : butacas) {
        if (i == 1)
            contador++;
    }

    Assert.assertThat(contador, is(7));
}

You can even do the comparison with lambda and stream expressions, it's simpler and more understandable.

@Test
public void validarButacasTest() {

    Integer[] butacas = { 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1 };
    int contador = (int) Arrays.asList(butacas).stream().filter(b -> b == 1).count();

    Assert.assertThat(contador, is(8));
}
    
answered by 10.08.2017 в 16:46