2011-04-21 84 views
3

我想设置一个限制为我在Java中使用的int值。我正在创建一个简单的医疗系统,我希望我的健康状况保持在0到100之间。我该怎么做?设置限制为一个int值

+0

为什么你需要设置一个限制? – Ishmael 2011-04-21 19:21:58

+0

我不希望自己的健康状态低于0或高于100. – Stan 2011-04-21 19:23:21

+1

我猜你想要的东西比'yourInt = Math.max(yourInt,100)'更复杂一些;',请你详细说明一下在这个问题上再多一点? – Aleadam 2011-04-21 19:24:28

回答

12

我建议你创建一个名为卫生级和您检查每一个时间,如果新的值设置,如果它满足约束条件:

public class Health { 

    private int value; 

    public Health(int value) { 
     if (value < 0 || value > 100) { 
     throw new IllegalArgumentException(); 
     } else { 
     this.value = value; 
     } 
    } 

    public int getHealthValue() { 
     return value; 
    } 


    public void setHealthValue(int newValue) { 
    if (newValue < 0 || newValue > 100) { 
     throw new IllegalArgumentException(); 
     } else { 
     value = newValue; 
    } 
    } 

} 
+0

谢谢,它完全解决了这个问题我想了。 (无法点击接受按钮,必须再等6分钟。) – Stan 2011-04-21 19:28:46

+1

'IllegalArgumentException'就是您通常想要用于这样的非法参数。对游戏中要做的事情进行建模的方法(例如添加或移除X健康而不超出边界)对于这样的课程也是关键。 – ColinD 2011-04-21 19:32:29

+0

是的,您也可以使用IllegalArgumentException而不是定制的HelathException。 – RoflcoptrException 2011-04-21 19:33:53

1

封装领域,并把支票setter方法。

int a; 

void setA(int a){ 
    if value not in range throw new IllegalArgumentException(); 
} 
0

在Java中没有办法限制原语。你唯一能做的就是为此编写一个包装类。当然,通过这样做,您将失去良好的操作员支持,并且必须使用方法(如BigInteger)。

4

使用getter/setter模型。

public class MyClass{ 
    private int health; 

    public int getHealth(){ 
     return this.health; 
    } 

    public int setHealth(int health){ 
     if(health < 0 || health > 100){ 
      throw new IllegalArgumentException("Health must be between 0 and 100, inclusive"); 
     }else{ 
      this.health = health; 
     } 
    } 
} 
0
public void setHealth(int newHealth) { 
    if(newHealth >= 0 && newHealth <= 100) { 
    _health = newHealth; 
    } 
} 
3

我想创建一个强制执行的类。

public class Health { 
    private int health = 100; 

    public int getHealth() { 
    return health; 
    } 

    // use this for gaining health 
    public void addHealth(int amount) { 
    health = Math.min(health + amount, 100); 
    } 

    // use this for taking damage, etc. 
    public void removeHealth(int amount) { 
    health = Math.max(health - amount, 0); 
    } 

    // use this when you need to set a specific health amount for some reason 
    public void setHealth(int health) { 
    if (health < 0 || health > 100) 
     throw new IllegalArgumentException("Health must be in the range 0-100: " + health); 
    this.health = health; 
    } 
} 

这样,如果你有Health一个实例,你知道一个事实,即它代表健康的有效量。我想你通常只想使用像addHealth这样的方法,而不是直接设置健康状况。

-3

没有意义创建一个特殊的类。 为了增加i,使用这样的:

公共无效specialIncrement(int i)以 { 如果(我< 100) 我++ }

+0

这个问题应该如何回答? – RoflcoptrException 2011-04-21 19:37:21

+0

没有真正执行它,因为它会很容易忘记和增加我没有使用专用增量器。 – 2011-04-21 19:46:24