Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java limit length integer

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;
}
like image 330
Spongi Avatar asked Dec 05 '22 15:12

Spongi


2 Answers

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);
like image 114
user2004685 Avatar answered Dec 20 '22 08:12

user2004685


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");
}  
like image 27
john16384 Avatar answered Dec 20 '22 07:12

john16384