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

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日

悬赏问题

  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 有关类的报错,在模块里调用另一个模块的方法下的变量时出错
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格
  • ¥15 kali linux用wget archive.kali.org/archive-key.asc指令下载签名无效(失败)
  • ¥15 openHarmony 利用c++程序在dayu210开发板上实现拉取RTSP视频流并且在屏幕上显示
  • ¥15 GD32H757的can通信配置
  • ¥20 nist随机数测试的问题