简体   繁体   中英

How does the charAt() method work with taking numbers from strings and putting them into new strings in Java?

public String getIDdigits()
    {
        String idDigits = IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1) + "";
        return idDigits;
    }

In this simple method, where IDnum is a 13 digit string consisting of numbers and is a class variable, the given output is never what I expect. For an ID number such as 1234567891234, I would expect to see 14 in the output, but The output is always a three-digit number such as 101. No matter what ID number I use, it always is a 3 digit number starting with 10. I thought the use of empty quotation marks would avoid the issue of taking the Ascii values, but I seem to still be going wrong. Please can someone explain how charAt() works in this sense?

Try this.

public String getIDdigits()
    {
        String idDigits = "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1);
        return idDigits;
    }

When you first adding a empty it's add char like String if you put it in end it first add in number mode(ASCII) and then convert will converts that to String .

You are taking a char type from a String and then using the + operator, which in this case behaves by adding the ASCII numerical values together.

For example, taking the char '1' , and then the char '4' in your code

IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)

The compiler is interpreting this as its ASCII decimal equivalents and adding those

49 + 52 = 101

Thats where your 3 digit number comes from.

Eradicate this with converting them back to string before concatenating them...

String.valueOf(<char>);

or

"" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)

You have to be more explicit about the string concatenation and so solve your statement like this:

String idDigits = "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1);

The result of adding Java chars, shorts, or bytes is an int:

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