0

Apologies for the rather vague question, I wasn't sure how else to phrase it.

I am a beginner to java and I decided to test myself by creating a program that helps you play the board game Monopoly by taking the role of the banker (handles transactions and keeps track of everyone's money).

The program first asks for the number of players, and then creates an object for each player that has a name and a certain amount of money (1500 at the start). All the player objects are then stored in an array (Player[] playerArray).

The game then starts, and the point of the program is that it keeps track of each players money and the players play the board game as normal. Whenever a transaction happens, for example, Player1 buys a house for 300, you press enter to start a transaction, enter in the payer (in this case, Player1), and the recipient (in this case, the bank).

(Please note that the bank is not a player object, but really just means that there is no other player recieving the money.)

This is where I ran into a problem. I created a method that asks the user for the recipient, and then checks it against all the existing player objects in playerArray to see if there is a match (and also checks if it is the bank), and it returns a String value, the name of the recipient if it matches, and "recipient is not valid" if it does not. I also created a similar method for the payer.

For some reason, no matter what I input, the program always returns the value as "recipient is not valid", even if I input the recipient as the name of an existing player object.

Here is the method I was having trouble with:

static String askAndCheckRecipient(Player[] playerArray) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Who is the recipient?: ");
        String recipient = scan.nextLine();
        for(Player player : playerArray) {
            if(recipient.toLowerCase() == player.getName().toLowerCase() || recipient.toLowerCase() == "bank") {
                return recipient;
            }
        }
        return "recipient is not valid";
    }

Here is the full code, if you need it: (Sorry for the lack of comments)

package monopolybanker;
import java.util.*;

public class Main {
    
    public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);
        
        System.out.println("How many players are playing the game?: ");
        int playerCount = scan.nextInt();
        scan.nextLine(); //to clear the scanner
        
        Player[] playerArray = new Player[playerCount];
        for(int i = 0; i<playerCount; i++) {
            System.out.println("What is the name of player "+(i+1)+"?: ");
            String nextPlayerName = scan.nextLine();
            playerArray[i] = new Player(nextPlayerName);
        }
        
        displayPlayerNamesAndMoney(playerArray);
        waitTillTransaction();
        System.out.println(askAndCheckRecipient(playerArray));
        System.out.println(askAndCheckPayer(playerArray));

    }

    static void displayPlayerNamesAndMoney(Player[] playerArray) {
        for(Player player : playerArray) {
            System.out.println(player.getName()+" | "+player.getMoney());
        }
    }
    
    static void waitTillTransaction() {
        Scanner scan = new Scanner(System.in);
        System.out.println();
        String var = "something";
        while(!var.isBlank()) {
            System.out.println("Press enter to start a transaction");
            var = scan.nextLine();
        }
    
    }
    
    static String askAndCheckRecipient(Player[] playerArray) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Who is the recipient?: ");
        String recipient = scan.nextLine();
        for(Player player : playerArray) {
            if(recipient.toLowerCase() == player.getName().toLowerCase() || recipient.toLowerCase() == "bank") {
                return recipient;
            }
        }
        return "recipient is not valid";
        

    }
    
    static String askAndCheckPayer(Player[] playerArray) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Who is the payer?: ");
        String payer = scan.nextLine();
        for(Player player : playerArray) {
            if(payer.toLowerCase() == player.getName().toLowerCase() || payer.toLowerCase() == "bank") {
                return payer;
            }
        }
        return "payer is not valid";
    }
}

public class Player {

    private String name;
    private int money = 1500;
    
    Player(String name) {
        this.name = name;
    }
    
    // Getters
    
    public String getName() {
        return name;
    }
    
    public int getMoney() {
        return money;
    }
    
    // Setters
    
    public void setMoney(int newmoney) {
        this.money = newmoney;
    }
    
}


  • 1
    In _Java_ you have to use the _[String#equals](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/String.html#equals(java.lang.Object))_ method to compare _String_ values. And, on that note, there is also a _[String#equalsIgnoreCase](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/String.html#equalsIgnoreCase(java.lang.String))_, also. – Reilas Jul 19 '23 at 12:10

1 Answers1

0

The key thing to understand is that Strings in Java are objects, not primitive types.

The equality operator == checks whether the two String objects have the same reference (i.e. they are the same object). This is usually not the case, even if two String objects have the same value.

Comparing the values of two String objects should be done via the .equals() method.

For example:

payer.toLowerCase() == player.getName().toLowerCase()

..should become:

payer.toLowerCase().equals(player.getName().toLowerCase())

phil76
  • 134
  • 7
  • 1
    please note that the question is a very old one on StackOverflow - there is no need to answer duplicates - from [answer]: "Not all questions can or should be answered here. Save yourself some frustration and avoid trying to answer questions which ... have already been asked and answered many times before." – user16320675 Jul 19 '23 at 12:13
  • 1
    ... which in turn should become `payer.equalsIgnoreCase(player.getName())` – tobias_k Jul 19 '23 at 12:19
  • Thanks for your comment, I'm aware that it's a common / old question, but I was trying to give the original poster a clearer explanation of the reason behind why .equals() works but == fails. – phil76 Jul 19 '23 at 12:19
  • Thanks for the help, this really clears things up – Hashim Bin Talha Jul 19 '23 at 12:23
  • I believe the confusion stems from the fact that _String_ values are referred to as a _scalar_ type. Most people inherently believe they could then just use _==_. – Reilas Jul 19 '23 at 13:09