I would like to key in my nirc
number e.g. S1234567I
and then put 1234567
individualy as a integer as indiv1
as cha
I know question is about char to int but this worth mentioning because there is negative in char too ))
From JavaHungry you must note the negative numbers for integer if you dont wana use Character.
Converting String to Integer : Pseudo Code
1. Start number at 0
2. If the first character is '-'
Set the negative flag
Start scanning with the next character
For each character in the string
Multiply number by 10
Add( digit number - '0' ) to number
If negative flag set
Negate number
Return number
public class StringtoInt {
public static void main (String args[])
{
String convertingString="123456";
System.out.println("String Before Conversion : "+ convertingString);
int output= stringToint( convertingString );
System.out.println("");
System.out.println("");
System.out.println("int value as output "+ output);
System.out.println("");
}
public static int stringToint( String str ){
int i = 0, number = 0;
boolean isNegative = false;
int len = str.length();
if( str.charAt(0) == '-' ){
isNegative = true;
i = 1;
}
while( i < len ){
number *= 10;
number += ( str.charAt(i++) - '0' );
}
if( isNegative )
number = -number;
return number;
}
}
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.
Take a look at Character.getNumericValue(ch).
The modern solution uses Unicode code point numbers rather than the outmoded char
type.
Here is an IntStream
, a successive stream of each character’s code point number, printing each of those numbers to console:
"S1234567I"
.codePoints()
.forEach( System.out :: println )
83
49
50
51
52
53
54
55
73
Show each character along with its code point number. To convert a code point number back into a character, call Character.toString while passing the integer: Character.toString( codePoint )
.
String s = Character.toString( 49 ) ; // Returns "1".
…and…
String s = Character.toString( 128_567 ) ; // Returns "
try {
int indiv1 = Integer.parseInt ("" + nric.charAt(1));
System.out.println(indiv1);
} catch (NumberFormatException npe) {
handleException (npe);
}
int indiv1 = Integer.parseInt(nric.charAt(1));