简体   繁体   中英

How do I verify that an integer value within a large number in a certain position is a certain value in Java?

I've searched all over and saw different variances. But neither seemed to work for me :( So in Java how can I check the value of a certain position of large integer? I want to have a check to ensure that the 1st position in any number like 678954 is a value of 4. What built in Java class is there to check the value of an integer within an certain position? I would assume there is something built in like .charAt for this? Like below I want to ensure the 1st position in the integer is a '0'. If I missed a previous answer to this same question that has happened before please excuse me. If so could you post the link from it in Stackoverflow? Oh I saw something about Character.getNumericValue, I tried that and got the same "int can not be dereferenced" error.

if(getEmployeeId().charAt(0) == '0')

Cheers!

String str = Integer.toString(getEmployeeId());
if(str.charAt(str.length() - 1) == '0')

Or, with mod,

if (getEmployeeId % 10 == 0)

You can apply your math skills and use / and % to check digits of a number without converting it to a string:

if (num % 10 == 4) {
    // The last digit is 4
}

if ((num/1000) % 10 == 7) {
    // Digit at position 4 is 7
}

The idea is to "shift" the decimal representation of the number by dividing it by a power of ten, and then get the last digit by computing the remainder after division by ten.

If I understand correctly, check out @Louis Wassermans answer. you need to convert an int to a string first in order to check the value using charAt(). I don't think charAt() works with ints.

Your problem is that in java integers are stored in binary. For example the number 678954 would be 10100101110000101010.

As you can see 10100101110000101010 does not have a character '4' inside of it. What you should do instead is to convert the integer to string so that you do string operations on it.

An easy way to do this is to use the Integer.toString(aInt) to convert your integers to strings first.

try changing your code from

if(getEmployeeId().charAt(0) == '0')

to

if(Integer.toString(getEmployeeId()).charAt(0) == '0')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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