简体   繁体   English

Java限制长度整数

[英]Java limit length integer

I am new in Java and I need some help. 我是Java的新手,我需要一些帮助。

Can someone tell me how I can set limit length to integer = 6 in this code. 有人能告诉我如何在此代码中将限制长度设置为整数= 6。

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: 根据下面的@EliSadoff评论,你也可以这样做:

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

You can then simply call this function like this: 然后你可以简单地调用这个函数:

checkLength(123456, 6);

"String.valueOf(id).length()" - checks the length of a int variable, which you receive in setId method parameter. “String.valueOf(id).length()” - 检查在setId方法参数中收到的int变量的长度。

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

In your setId method add a check: 在你的setId方法中添加一个检查:

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

validate the inp before assigning it 在分配之前验证inp

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

In java numbers like int don't have the length. 在像int这样的java数字中没有长度。 Although Integer is a class, there is no length() function -- see the Java docs. 尽管Integer是一个类,但没有length()函数 - 请参阅Java文档。 So, to find the length, you have to convert Integer to String using String.valueOf(Integer_value) . 因此,要查找长度,必须使用String.valueOf(Integer_value)将Integer转换为String。 So, you can do like below: 所以,你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM