薰 风 2023-06-19 19:15 采纳率: 63.3%
浏览 32

JAVA在一个类中,如何修改另一个类中的静态常量(字符串类型)的值

1给Penguin类提供SEX_MALE和SEX_FEMALE两个静态常量,分别取值"Q仔"或"Q妹",
2修改Test类,使用静态常量对性别进行赋值
3修改企鹅的性别只能取值"雄"或"雌",通过修改静态常量值实现该需求

输入图 在Test类中 请选择企鹅的性别:(1Q仔,2Q妹) 2

img

实现效果图 性别是雌

img

  • 写回答

1条回答 默认 最新

  • threenewbee 2023-06-19 19:49
    关注
    public class Penguin {
        private String name;
        private int health;
        private int intimacy;
        private String gender;
    
        public Penguin(String name, int health, int intimacy, String gender) {
            this.name = name;
            this.health = health;
            this.intimacy = intimacy;
            this.gender = gender;
        }
    
        public String getName() {
            return name;
        }
    
        public int getHealth() {
            return health;
        }
    
        public int getIntimacy() {
            return intimacy;
        }
    
        public String getGender() {
            return gender;
        }
    
        public void setGender(String gender) {
            if (gender.equals("雄") || gender.equals("雌")) {
                this.gender = gender;
            } else {
                System.out.println("性别只能为“雄”或“雌”,修改未成功!");
            }
        }
    }
    
    public class Test {
        public static final String SEX_MALE = "Q仔";
        public static final String SEX_FEMALE = "Q妹";
    
        public static void main(String[] args) {
            System.out.println("请选择企鹅的性别:(1: Q仔, 2: Q妹)");
            Scanner scanner = new Scanner(System.in);
            int choice = scanner.nextInt();
    
            String gender;
            if (choice == 1) {
                gender = SEX_MALE;
            } else if (choice == 2) {
                gender = SEX_FEMALE;
            } else {
                System.out.println("输入无效!");
                return;
            }
    
            Penguin penguin = new Penguin("企鹅", 100, 0, gender);
    
            System.out.println("名字:" + penguin.getName());
            System.out.println("健康度:" + penguin.getHealth());
            System.out.println("亲密度:" + penguin.getIntimacy());
            System.out.println("性别:" + penguin.getGender());
        }
    }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 6月19日