Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: charAt convert to int?

Tags:

java

I would like to key in my nirc number e.g. S1234567I and then put 1234567 individualy as a integer as indiv1 as charAt(1), indiv2 as charAt(2), indiv as charAt(3), etc. However, when I use the code below, I can't seem to get even the first number out? Any idea?

  Scanner console = new Scanner(System.in);
  System.out.println("Enter your NRIC number: ");

  String nric = console.nextLine();

  int indiv1 = nric.charAt(1);
  System.out.println(indiv1);
like image 665
sling Avatar asked Apr 13 '10 06:04

sling


People also ask

Can I use charAt to integer in Java?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

Can I use charAt for integers?

NOTE: We can pass either a postive or negative integer based on which we shall expect the output. The output for positive integer passed while executing the charAt() in Java is the character value if the index is in the range of the length of the string.

Does charAt return ASCII value?

charAt(n)) gives the ASCII value. For example, if s='110', then s. charAt(0)=1 and Integer. valueOf(s.


2 Answers

You'll be getting 49, 50, 51 etc out - those are the Unicode code points for the characters '1', '2', '3' etc.

If you know that they'll be Western digits, you can just subtract '0':

int indiv1 = nric.charAt(1) - '0';

However, you should only do this after you've already validated elsewhere that the string is of the correct format - otherwise you'll end up with spurious data - for example, 'A' would end up returning 17 instead of causing an error.

Of course, one option is to take the values and then check that the results are in the range 0-9. An alternative is to use:

int indiv1 = Character.digit(nric.charAt(1), 10);

This will return -1 if the character isn't an appropriate digit.

I'm not sure if this latter approach will cover non-Western digits - the first certainly won't - but it sounds like that won't be a problem in your case.

like image 135
Jon Skeet Avatar answered Oct 21 '22 21:10

Jon Skeet


Take a look at Character.getNumericValue(ch).

like image 37
starblue Avatar answered Oct 21 '22 21:10

starblue