0

I am so confused as to what is happening. I have a Java application for android and am having trouble with one if statement. The if statement is within a for loop that is looping through an ArrayList of objects that I have created earlier in the code. Each object has a type variable which is a string and a method to access the variable. In the for loop I printed out the variable for each object to check what it is, and it prints out "0" as a string. I then check it with an if statement within that for loop stating, if b.getType() == "0", and while I know that it is for sure 100% that the statement is true, it will not run the code within made sure by the fact that I had it print out the word "true" if it ran the code. I have no idea what is happening.

  public Level(String level, Bitmap[] images){
    String[] types = level.split(" ");
    this.images = images;
    int x = 60;
    int y = 48;
    for(int i = 0; i < 276; i++){ //creates new block objects based on the text file
        blocks.add(new Block(x, y, types[i]));
        x += 32;
        if(x >= 796){
            x = 60;
            y += 32;
        }
    }
}

This is where I initialized the objects, passing in a string value of type to the block object.

 public void draw(Canvas canvas){
    for(Block b: blocks){ //loops through the blocks and draws them to the canvas
        System.out.println(b.getType());
       if(b.getType() == "1"){
           System.out.println("true");
           canvas.drawBitmap(images[1], b.getX(), b.getY(), null);
       }
    }
}

This is the block of code that is being run and is causing me much trouble.

public class Block {

private int x;
private int y;
private String type;

public Block(int x, int y, String type){
    this.x = x;
    this.y = y;
    this.type = type;
}


public int getX(){
    return x;
}

public int getY(){
    return y;
}

public String getType(){
    return type;
}

}

I/System.out﹕ 0

This is the block class where type is stored. Below is what is printed out as it says in System.out.println(b.getType()); Much help would be appreciated.

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73

2 Answers2

1

== compares pointers to strings, not strings themselves. Use equals:

"0".equals(b.getType())
Ishamael
  • 12,583
  • 4
  • 34
  • 52
0

== validates for reference equality.

.equals() validates for value equality

change code to below,

b.getType().equals("0")

String#equals

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116