有没有一种方法可以在Java中创建范围?

时间:2019-09-25 18:45:47

标签: java

我正在创建虚拟猫。用户应该能够对其进行命名,并具有与用户交互的三个类别,即健康,食物,幸福。范围是(最低)1-50(最高)。int值是30。理想情况下,用户应该可以通过交互作用来升高或降低类别。

如何创建此范围并将其声明为最大值50,将最小值声明为1?

我已经声明了这三个类别。

String catName;
int food = 30;
int health = 30;
int happiness = 30;

System.out.println(" type cat name");

catName = input.nextLine();

4 个答案:

答案 0 :(得分:0)

是的,正如@MC Emperor在评论中所说的,Java是OO语言,因此您应该这样使用它。例如,您可以创建以下类(只是为您提供启动的起点):

public class VirtualCat{

    private int food;

    //... other properties, constructors etc

    // here validate the modification of the property
    public void increaseFood(){
        if(food + 1 > 50){
            throw new Exception("Invalid value for food");
        } else {
            food ++;
        }
    }

    public void decreaseFood(){
        if(food - 1 < 1){
            throw new Exception("Invalid value for food");
        } else {
            food --;
        }
    }
}

答案 1 :(得分:0)

对于有权访问Guava Java库的用户,请考虑:

https://guava.dev/releases/19.0/api/docs/com/google/common/collect/Range.html

答案 2 :(得分:0)

就像其他人已经写过的一样,Java是一种面向对象的编程语言,您应该利用它。

确保值保持在定义范围内的一种好方法是实现一种可以设置上限,下限和可变值的类型。一个基本的实现可能看起来像这样:

public class RangedValue {
    private final int lowerLimit;
    private final int upperLimit;
    private int value;

    public RangedValue(int lowerLimit, int upperLimit, int value) {
        if (lowerLimit >= upperLimit) {
            throw new IllegalArgumentException("The lowerLimit must be less " +
                    "than the upperLimit!");
        }
        this.lowerLimit = lowerLimit;
        this.upperLimit = upperLimit;
        this.value = RangedValue.ensureRange(value, upperLimit, lowerLimit);
    }

    /**
     * Helper method to ensure that a value stays within the defined range.
     *
     * @param value      The value to be kept in the defined range
     * @param upperLimit The upper limit of the range
     * @param lowerLimit The lower limit of the range
     * @return The value or the lowerLimit or the upperLimit
     */
    private static int ensureRange(int value, int upperLimit, int lowerLimit) {
        if (value > upperLimit) {
            return upperLimit;
        } else if (value < lowerLimit) {
            return lowerLimit;
        }

        return value;
    }

    public int increaseValueBy(int value) {
        int increased = this.value + value;
        this.value = RangedValue.ensureRange(increased, upperLimit, lowerLimit);
        return this.value;
    }

    public int reduceValueBy(int value) {
        return increaseValueBy(-value);
    }

    public int setValue(int value) {
        return RangedValue.ensureRange(value, upperLimit, lowerLimit);
    }

    public int getLowerLimit() {
        return lowerLimit;
    }

    public int getUpperLimit() {
        return upperLimit;
    }

    public int getValue() {
        return value;
    }
}

然后您可以将此类用于现有代码:

RangedValue food = new RangedValue(0, 50, 30);
RangedValue health = new RangedValue(0, 50, 30);
RangedValue happiness = new RangedValue(0, 50, 30);

System.out.println(" type cat name");

catName = input.nextLine();

当然,您也可以在单独的类中定义猫,但这取决于您。

答案 3 :(得分:0)

我了解您是否刚开始使用Java。 编写程序的正确方法是使用OOP。那就是..创建Virtual Cat的对象:

public class VirtualCat {
    private String catName;
    private int food;
    private int health;
    private int happiness;

    public VirtualCat(String catName){
        this.catName = catName;
        this.food = 30;
        this.health = 30;
        this.happiness = 30;
    }

    public String increaseFood(){
        if(this.food+1 > 50)
            return "Error. Food range is [1-50].";
        else{
            this.food++;
            return "Food increased.";
        }
    }

    public String increaseHealth(){
        if(this.health+1 > 50)
            return "Error. Health range is [1-50].";
        else{
            this.health++;
            return "Health increased.";
        }
    }

    public String increaseHappiness(){
        if(this.happiness+1 > 50)
            return "Error. Happiness range is [1-50].";
        else{
            this.happiness++;
            return "Happiness increased.";
        }
    }

    public String decreaseFood(){
        if(this.food-1 < 0)
            return "Error. Food range is [1-50].";
        else{
            this.food--;
            return "Food decreased.";
        }
    }

    public String decreaseHealth(){
        if(this.health-1 < 0)
            return "Error. Health range is [1-50].";
        else{
            this.health--;
            return "Health decreased.";
        }
    }

    public String decreaseHappiness(){
        if(this.happiness-1 < 0)
            return "Error. Happiness range is [1-50].";
        else{
            this.happiness--;
            return "Happiness decreased.";
        }
    }

    @Override
    public String toString() {
        return "VirtualCat{" + "catName=" + catName + ", food=" + food + ", health=" + health + ", happiness=" + happiness + '}';
    }
}

因此,您的主程序必须像这样:

public static void main(String[] args) {
        int answer = 1;
        int increaseOrDecrease = 0;
        VirtualCat virtualCat = new VirtualCat(JOptionPane.showInputDialog(null, "Please insert cat name"));

        while(answer == 1){
            System.out.println("Actual status for virtual cat: "+virtualCat.toString());
            increaseOrDecrease = Integer.parseInt(JOptionPane.showInputDialog(null, "Do you want to increase food? Type 1 for increase, type 2 for decrease"));
            if(increaseOrDecrease == 1)
                System.out.println(virtualCat.increaseFood());
            else if(increaseOrDecrease == 2)
                System.out.println(virtualCat.decreaseFood());
            else
                System.out.println("Incorrect option. It need to be 1 or 2");

            increaseOrDecrease = Integer.parseInt(JOptionPane.showInputDialog(null, "Do you want to increase health? Type 1 for increase, type 2 for decrease"));
            if(increaseOrDecrease == 1)
                System.out.println(virtualCat.increaseHealth());
            else if(increaseOrDecrease == 2)
                System.out.println(virtualCat.decreaseHealth());
            else
                System.out.println("Incorrect option. It need to be 1 or 2");

            increaseOrDecrease = Integer.parseInt(JOptionPane.showInputDialog(null, "Do you want to increase happiness? Type 1 for increase, type 2 for decrease"));
            if(increaseOrDecrease == 1)
                System.out.println(virtualCat.increaseHappiness());
            else if(increaseOrDecrease == 2)
                System.out.println(virtualCat.decreaseHappiness());
            else
                System.out.println("Incorrect option. It need to be 1 or 2");

            answer = Integer.parseInt(JOptionPane.showInputDialog(null, "Do you want continue? Type 1 for yes, type 2 for no"));
        }
        System.out.print("Final status for virtual cat: "+virtualCat.toString());
    }