1

I'm trying to change certain index values of this boolean array to false and it does change but when re-displayed in another method it doesn't print properly.

This is for an assignment at school. I've check memory locations and they are the same.

import java.util.Scanner;
import java.util.Arrays;
public class Lab11avst
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        final int MAX = 100;
        boolean primes[];
        primes = new boolean[MAX];
        computePrimes(primes);
        displayPrimes(primes);
    }

    public static void computePrimes(boolean list[])
    {
        Arrays.fill(list, true);
        for (int i = 1; i < list.length ; i++)
        {
            if (list[i] = true)
            {
                for (int j = (i+1); j < 20; j+=(i+1))
                {
                    list[j] = false;
                    System.out.println( j+" "+list[j]);
                }
            }
        }
    }
    public static void displayPrimes( boolean x[])
    {
        for(int y = 1; y< (x.length); y+=1)
        {
            if(x[y] =true)
            {
                System.out.print(y+ " ");
            }
        }
    }
}
  • 2
    wrong duplicate. You're doing `if (foo = true)` which assigns true to foo – Hovercraft Full Of Eels Jan 23 '19 at 02:58
  • 1
    You don't need to compare booleans anyway. `if(x[y])` is the same thing as `if(x[y] == true)`. Comparisons produce booleans, but you already have a boolean. – RaminS Jan 23 '19 at 03:00
  • Another relevant question you might want to look at: https://stackoverflow.com/questions/2661110/is-it-bad-to-explicitly-compare-against-boolean-constants-e-g-if-b-false-i – default locale Jan 23 '19 at 03:04

1 Answers1

0

The problem is inside your displayPrimes and computePrimes methods. You have an if statement in both, if(x[y] =true) and if (list[i] = true) respectively. The operator used for comparison is two equals signs, or ==. A single equal sign is an assignment operator that returns the new value of x[y] or list[i]. Think of = as a function that receives two parameters and returns the second parameter with the first parameter modified. Since x[y] and list[i]is modified to true, it will always pass your if statement check. To fix this, replace if(x[y] =true) with if(x[y]) and if (list[i] = true) with if (list[i]).

Gymhgy
  • 338
  • 4
  • 11