0

I am trying to make Memory Puzzle game. So I have Card.java class:


import javafx.geometry.Pos;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;


public class Card extends StackPane {
    private Text text = new Text ();
    private String path;
    public Card (String p){
        this.path=p;
        Rectangle rectangle = new Rectangle (80,80);
        rectangle.setFill (null);
        rectangle.setStroke (Color.BLACK);
        text.setText (this.path);
        setAlignment (Pos.CENTER);
        getChildren ().addAll(rectangle, text);
        hidden ();
    }
    public String getPath () {
        return path;
    }
    public boolean isShown(){
       return text.getOpacity () ==1;
    }
    public void shown(){
        text.setOpacity (1);
    }
    public void hidden(){
        text.setOpacity (0);
    }
}

Main.java:

[...]
List<Card> cards = new ArrayList<> ();
        for ( int i = 1; i <= numberOfPairs; i++ ) {
            cards.add (new Card (String.valueOf (i)));
            cards.add (new Card (String.valueOf (i)));
        }
        Collections.shuffle (cards);
        int i = 0;
        int j = 0;
        for ( Card card : cards ) {
            card.setOnMouseClicked (e -> cardClicked (card));
            if (i == this.cardsInOneRow) {
                j++;
                i = 0;
            }
            gridpane.add (card, i, j);
            i++;
        }
[...]
    private Card selectedCard = null;
    private int clickCounter = 0;
    public void cardClicked (Card card) {
        if (card.isShown () || clickCounter == 2) {
            return;
        }
        clickCounter++;
        if (selectedCard == null) {
            selectedCard = card;
            card.shown ();
        } else {
            card.shown ();
                if (card.getPath ()!=selectedCard.getPath ()) {
                selectedCard.hidden ();
                card.hidden ();
                }
                selectedCard=null;
                clickCounter=0;
            }
    }

In Main.java I'm creating couple pairs of cards, setting on mouse click function and placing them inside GridPane. Then I'm trying to compare String path from 2 cards and it results in false every time. I have no clue how to fix it.

Demonox
  • 1
  • 1

1 Answers1

0

Try this: if(!card.getPath().equals(selectedCard.getPath())) {}.

If you want to compare the value of Strings you have to use equals().

See here why: String.equals versus ==