Java Integer String Length

I am new to Java and I need help.

Can someone tell me how I can set the maximum length to integer = 6 in this code.

for instance

id = 124973 

public void setId(int id) {
    this.id = id;
}
+4
source share
5 answers

One way to do this:

public boolean checkLength(int id, int length) {
    return 0 == (int)(id / Math.pow(10, length));
}

EDIT:

According to the @EliSadoff comment below, you can also do something like this:

public boolean checkLength(int id, int length) {
    return Math.log10(id) < length;
}

Then you can simply call this function as follows:

checkLength(123456, 6);
+6
source

"String.valueOf (id) .length ()" - checks the length of the int variable that you get in the setId method parameter.

public void setId(int id){
    if(6 >= String.valueOf(id).length())
       this.id= id;
    else
       //do something if the received id length is greater than max
}
+3
source

setId :

if (id >= 1000000 || id < 0) {
   throw new IllegalArgumentException("id must be max 6 digits and cannot be negative");
}  
+3

inp

public void setId(int id){
    if(id>0 && id<=999999){
        this.id= id;
    }else{
        this.id= 0;
    }
}
+2

In java numbers like int, there is not enough length. Although Integer is a class, the length () function is missing - see Java Docs. So, to find the length, you need to convert Integer to String with String.valueOf(Integer_value). So you can do as below:

Public void limit(Integer a) {
if(String.valueOf(a)<=6) {
    //do your logic
}
else {
//printout Integer length limit exceeded
}
}
0
source

Source: https://habr.com/ru/post/1666848/


All Articles