Boostr



0 votes
16 views
I am trying to fetch second digit from a long variable.

long mi = 110000000;
int firstDigit = 0;
String numStr = Long.toString(mi);
for (int i = 0; i < numStr.length(); i++) {
    System.out.println("" + i + " " + numStr.charAt(i));
    firstDigit =  numStr.charAt(1);
}
When I am printing firstDigit =  numStr.charAt(1) on console. I am getting 1 which is expected but when the loop finishes firstDigit has 49. Little confused why.
asked Dec 30, 2017 in Core java by Amrendra | 16 views



2 Answers

0 votes
Best answer
You got confused because 49 is ASCII value of integer 1. So you may parse character to integer then you can see integer value.

    Integer.parseInt(String.valueOf(mi).charAt(1)):
answered Dec 30, 2017 by Amrendra
0 votes
Because 49 is the ASCII value of char '1'.

So you should not assign a char to int directly.

And you don't need a loop here which keeps ovveriding the current value with charAt(1) anyway.

int number = numStr.charAt(1) - '0'; // substracting ASCII start value
The above statement internally works like 49 -48 and gives you 1.

If you feel like that is confusious, as others stated use Character.getNumericValue();

Or, although I don't like ""+ hack, below should work

int secondDigit = Integer.parseInt("" + String.valueOf(mi).charAt(1));
answered Dec 30, 2017 by Amrendra

Related Questions



Welcome to Knowledge Boostr, where you can ask questions and receive answers from other members of the community.
This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

http://boostr.in Q&A for professional and enthusiast programmers http://boostr.in Q&A for professional and enthusiast programmers http://boostr.in Q&A for professional and enthusiast programmers http://boostr.in Q&A for professional and enthusiast programmers


23,494 questions
40,169 answers
12 comments
23,609 users