Java新手。我知道字符串是不可变的,但我不明白为什么输出就是这样的。
目标:我试图向用户询问一个问题“你想成为什么类?”,用户回答。他们的答案存储在一个字符串变量(classEntered)中,并传递给setClass方法,该方法返回启动HP并根据输入到classEntered的内容启动gold。
问题:当用户输入他们想要的角色(即术士或战士)时,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);
}
}
答案 0 :(得分:1)
String
区分大小写。当您的玩家输入他的课程时,他必须在完全中将其写入setClass
API进行比较。
其次,您必须使用equals
方法来比较字符串内容。
if(playerClass.equals("Warlock"))
{
startingHP = 100;
startingGold = 25;
}
else if (playerClass.equals("Warrior"))
{
startingHP = 150;
startingGold = 30;
}
在您的代码中,代码未输入IF语句的任何分支。
其他:
equalsIgnoreCase
来比较字符串,而不是equals