设置int值的限制 [英] Setting a limit to an int value
本文介绍了设置int值的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Java中设置一个 int
值的限制。我正在创建一个简单的健康系统,我希望我的健康状况保持在0到100之间。我该怎么做?
I want to set a limit to an int
value I have in Java. I'm creating a simple health system, and I want my health to stay between 0 and 100. How can I do this?
推荐答案
我建议您创建一个名为Health的类,如果满足约束条件,则每次都检查是否设置了新值:
I would recommend that you create a class called Health and you check every time if a new value is set if it fulfills the constraints :
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;
}
}
}
这篇关于设置int值的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文