0

I'm trying to compare the values of the boolean (all of which are 0) to the values of this string array data[] = "1,0,0,0,0,0,0,0,0,0,0,0,1". This is my code:

recipeIngrediants = new boolean[numberOfCuisines][numberOfIngrediants];
        int i = 0;
        while(file.hasNextLine()){
            String temp = file.nextLine();
            String[] data = temp.split(",");
        for(int j=0; j < recipeIngrediants.length; j++){
            String c = data[j];
            if(c == "1"){
                recipeIngrediants[i][j] = true;
            }
            else{
                recipeIngrediants[i][j] = false;
            }
        }
        i++;
     }

I get an error saying that it is a type mismatch. EDIT: Fixed the type mismatch error but it still gives me a value of false for all values in the boolean

Question:

How else can I compare these values to get the 2D array of recipeIngrediants to equal true at whatever position in data has a 1?

  • 1
    You are assigning `"1"` to `c` instead of comparing the values... Make it `c == "1"` in the `if` condition. No, better use `c.equals("c")` – deHaar Nov 27 '18 at 15:38
  • 5
    First of all make sure you are not incorrectly using = instead of ==, secondly strings are tested for equality using .equals() and not == – Joakim Danielson Nov 27 '18 at 15:38
  • 1
    `c = "1"` is assigning `"1"` to the variable `c`. The return value of an assignment is the value being assigned; so `if (c = "1" != null)` is effective `c = "1"; if (true)`. `String` comparisons (and all other `Object`s) should be done with `Object.equals` in java. – BeUndead Nov 27 '18 at 15:38

1 Answers1

0

I think that you want to assign to the array items true for every string c that evaluates to "1" and false otherwise:

recipeIngrediants = new boolean[numberOfCuisines][numberOfIngrediants];
int i = 0;
while(file.hasNextLine()){
    String temp = file.nextLine();
    String[] data = temp.split(",");
    for(int j=0; j < recipeIngrediants.length; j++){
        String c = data[j];
        recipeIngrediants[i][j] = (c != null) && (c.equals("1"));
    }
    i++;
}
forpas
  • 160,666
  • 10
  • 38
  • 76
  • Ahh, so using the null check and the .equals operator instead of "==" worked. Although because its a jagged array at other points i needed to add recipeIngrediants[i].length to the for loop. Thank you! – Kyle Croumer Nov 27 '18 at 16:00
  • @KyleCroumer I don't know if you really need the null check. I saw it in your code. Of course you need to check not to bypass the length of the array. – forpas Nov 27 '18 at 16:02