英文:
How to set an attributes in departments to be between certain numbers?
问题
I'm trying to set the attribute "Hour" to be between the numbers 0 and 23, How?
我想将属性“Hour”设置为介于0和23之间的数字,如何实现?
I'm trying to do it with a set function. So any answers to HOW?
我想使用一个设置函数来实现。有关如何实现的任何答案?
英文:
I'm trying to set the attribute "Hour" to be between the numbers 0 and 23, How?
I'm trying to do it with a set function. So any answers to HOW?
public class Time {
private int Hour;
private int minute;
}//Class
答案1
得分: 0
如果我理解正确,您希望保护这些变量,以便它们不能被设置为无效值。所以 Hour
应该只能在 0 到 23 之间,而 minute
应该只能在 0 到 59 之间。
public class Time {
private int Hour;
private int minute;
public int getHour() {
return this.Hour;
}
public int getMinute() {
return this.minute;
}
public void setHour(int hour) {
// this.Hour = Math.min(Math.max(0, hour), 23);
this.Hour = hour > 23 ? 23 : hour < 0 ? 0 : hour;
}
public void setMinute(int minute) {
// this.minute = Math.min(Math.max(0, minute), 59);
this.minute = minute > 59 ? 59 : minute < 0 ? 0 : minute;
}
}
英文:
If I am understanding this correctly. You want to guard the variables so they cannot be set to invalid values. So Hour
should only be between 0 and 23, and minute
between 0 and 59.
public class Time {
private int Hour;
private int minute;
public int getHour() {
return this.Hour;
}
public int getMinute() {
return this.minute;
}
public void setHour(int hour) {
// this.Hour = Math.min(Math.max(0, hour), 23);
this.Hour = hour > 23 ? 23 : hour < 0 ? 0 : hour;
}
public void setMinute(int minute) {
// this.minute = Math.min(Math.max(0, minute), 59);
this.minute = minute > 59 ? 59 : minute < 0 ? 0 : minute;
}
}
答案2
得分: 0
如果您不希望使用数学,那么您可以在您的函数中添加简单的条件。
private int hour;
private int minute;
public void setHour(int value) {
if (value > 23) {
value = 23;
}
if (value < 0) {
value = 0;
}
this.hour = value;
}
public void setMinute(int value) {
if (value > 59) {
value = 59;
}
if (value < 0) {
value = 0;
}
this.minute = value;
}
英文:
If you don't wish to use Math then you can add simple condition into your function.
private int hour;
private int minute;
public void setHour(int value) {
if (value > 23) {
value = 23;
}
if (value < 0) {
value = 0;
}
this.hour = value;
}
public void setMinute(int value) {
if (value > 59) {
value = 59;
}
if (value < 0) {
value = 0;
}
this.minute = value;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论