Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 828
Scuffed Newton Avatar asked Dec 10 '22 00:12

Scuffed Newton


2 Answers

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)
like image 59
james Avatar answered May 06 '23 19:05

james


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.

like image 44
SMortezaSA Avatar answered May 06 '23 18:05

SMortezaSA