开发者社区 问答 正文

如何在Java菜单中限制用户操作?

我正在尝试创建一个菜单选项,以便用户通过输入数字与cat进行交互。但是在选项== 1下出现红色错误。另外,我想限制用户,使其仅当健康水平低于60时才可以使猫过饱,他们才可以喂养它。我还想为用户提供一个退出程序的选项。

enter code here String options; System.out.println("pick an option "); System.out.println(" Option 1 feed cat "); System.out.println(" Option 2 play with cat"); System.out.println(" Option 3 give cat bath"); option = input.nextLine(); if(option == 1) { food += 10; happiness -= 15; } else if (option ==2) { happiness += 12; health += 25; }

展开
收起
被纵养的懒猫 2019-09-30 14:57:22 513 分享 版权
阿里云 AI 助理回答

要解决你的问题,我们需要做几件事:修正语法错误、添加条件判断以限制喂猫操作、以及提供一个退出程序的选项。下面是一个修改后的示例代码,使用Java编写:

import java.util.Scanner;

public class CatInteraction {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int health = 100; // 假设初始健康值为100
        int happiness = 50; // 初始幸福值
        int food = 0; // 食物量

        while (true) {
            System.out.println("Pick an option: ");
            System.out.println("Option 1: Feed cat");
            System.out.println("Option 2: Play with cat");
            System.out.println("Option 3: Give cat a bath");
            System.out.println("Option 4: Exit program");

            String option = input.nextLine();

            if ("1".equals(option)) {
                if (health < 60) {
                    food += 10;
                    happiness -= 15;
                    System.out.println("You fed the cat. Food increased by 10, happiness decreased by 15.");
                } else {
                    System.out.println("You can't feed the cat. Its health level is above 60.");
                }
            } else if ("2".equals(option)) {
                happiness += 12;
                // 注意:这里没有直接修改health的语句,根据你的描述应该是不需要改变health值
                System.out.println("You played with the cat. Happiness increased by 12.");
            } else if ("3".equals(option)) {
                // 这里假设给猫洗澡会增加其健康值,但你原始代码中未给出如何处理health和food
                // 因此我保持了原有逻辑不变,仅作为示例
                happiness += 25;
                System.out.println("You gave the cat a bath. Happiness increased by 25.");
            } else if ("4".equals(option)) {
                System.out.println("Exiting the program...");
                break; // 退出循环,结束程序
            } else {
                System.out.println("Invalid option. Please choose again.");
            }

            // 打印当前状态(可选)
            System.out.println("Current status: Health=" + health + ", Happiness=" + happiness + ", Food=" + food);
        }

        input.close();
    }
}

这段代码做了以下修改: 1. 使用"1".equals(option)而不是option == 1来比较字符串,因为input.nextLine()返回的是字符串。 2. 添加了一个条件判断,只有当猫的健康水平低于60时,用户才能选择喂猫。 3. 添加了一个退出程序的选项(Option 4)。 4. 在每个选项执行后打印当前状态,以便于理解程序运行结果(这一步是可选的,用于调试或用户体验)。

请确保根据你的实际需求调整健康值、幸福值等变量的初始化及更新逻辑。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答