I am new in Java and I need some help.
Can someone tell me how I can set limit length to integer = 6 in this code.
For example
id = 124973
public void setId(int id) {
this.id = id;
}
One way to do it is like this:
public boolean checkLength(int id, int length) {
return 0 == (int)(id / Math.pow(10, length));
}
EDIT:
As per @EliSadoff comment below, you can also do something like this:
public boolean checkLength(int id, int length) {
return Math.log10(id) < length;
}
You can then simply call this function like this:
checkLength(123456, 6);
In your setId
method add a check:
if (id >= 1000000 || id < 0) {
throw new IllegalArgumentException("id must be max 6 digits and cannot be negative");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With