4
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?

3 Answers3

5

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.

SMortezaSA
  • 579
  • 1
  • 15
5

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 the ASCII decimal values 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)
james
  • 633
  • 1
  • 13
3

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:

SMortezaSA
  • 579
  • 1
  • 15
CodeScale
  • 2,301
  • 1
  • 9
  • 16