New to Java. I understand that strings are immutable, but I don't understand why the output here is the way it is.
The goal: I'm trying to ask a user a question "What class do you want to be?", the user answers. Their answer is stored in a string variable (classEntered), and passed into the setClass method which returns starting HP and starting gold based on what was input into classEntered.
The problem: When The user enters what kind of character they want to be (i.e. warlock or warrior), playerClass gets updated properly. But the output (startingHP / startingGold) do not respond correctly.
Here is the code:
class Player {
String playerName;
String playerClass;
int startingGold;
int startingHP;
public void setName(String playerName){
this.playerName = playerName;
}
public void setClass(String newClass){
playerClass = newClass;
if(playerClass == "Warlock"){
startingHP = 100;
startingGold = 25;
}else if (playerClass == "Warrior"){
startingHP = 150;
startingGold = 30;
}
}
}
public class App {
public static void main(String[] args) {
// practice code: if playerClass defined this way the output is correct
Player player1 = new Player();
player1.setName("Jordan");
player1.setClass("Warlock");
System.out.println("Your name is: " + player1.playerName);
System.out.println("You're a " + player1.playerClass);
System.out.println("Your starting HP is " + player1.startingHP + " your starting gold is " + player1.startingGold);
Player player2 = new Player();
player2.setName("Jorel");
Scanner sc = new Scanner(System.in);
System.out.println("What class do you choose? ");
String classEntered = sc.nextLine();
player2.setClass(classEntered);
System.out.println("testing " + player2.playerClass);
//output is incorrect when playerClass defined via scanner
System.out.println("Your name is: " + player2.playerName);
System.out.println("You're a " + player2.playerClass);
System.out.println("Your starting HP is " + player2.startingHP + " your starting gold is " + player2.startingGold);
}
}