将用户输入定义的字符串变量传递给Java中的setter方法时,输出不正确

时间:2013-10-07 16:18:01

标签: java input

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);
        }

    }

1 个答案:

答案 0 :(得分:1)

Java中的

String区分大小写。当您的玩家输入他的课程时,他必须在完全中将其写入setClass API进行比较。

其次,您必须使用equals方法来比较字符串内容。

if(playerClass.equals("Warlock"))
{
    startingHP = 100;
    startingGold = 25;
}
else if (playerClass.equals("Warrior"))
{
    startingHP = 150;
    startingGold = 30; 
}

在您的代码中,代码未输入IF语句的任何分支。

其他:

  • 为您的类使用常量,甚至使用单独的类/枚举。
  • 为HP和Gold制作装订器和吸气剂。尊重封装。
  • 例如,如果他输入“elf”,请确保告诉使用该类不存在。
  • 要使您的课程不区分大小写,请使用equalsIgnoreCase来比较字符串,而不是equals