Java新手。我知道字符串是不可变的,但我不明白为什么这里的输出是这样的。
目标:我试图问用户一个问题“你想上什么课?”,用户回答。他们的答案存储在一个字符串变量 (classEntered) 中,并传递给 setClass 方法,该方法根据输入到 classEntered 的内容返回起始 HP 和起始金。
问题:当用户输入他们想要成为什么样的角色(即术士或战士)时,playerClass 会正确更新。但是输出(startingHP / startingGold)没有正确响应。
这是代码:
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);
}
}