Java: convert charAt to int?

I would like to indicate a number nirc, for example. S1234567Iand then put 1234567individualy as an integer like indiv1how charAt(1), indiv2how charAt(2), indivhow charAt(3), etc. However, when I use the code below, I do not seem to get even the first number? 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);
+5
source share
5 answers

You will get 49, 50, 51, etc. are Unicode code codes for the characters "1", "2", "3", etc.

If you know that they will be western numbers, you can simply subtract "0":

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

, , - - , "A" 17 , .

, - , , 0-9. :

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

-1, .

, - , , , - , .

+15
try {
   int indiv1 = Integer.parseInt ("" + nric.charAt(1));
   System.out.println(indiv1);
} catch (NumberFormatException npe) {
   handleException (npe);
}
0

, char int, , char ))

From JavaHungry, you should mark negative numbers for integers if you are not using Symbol.

Convert 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;
    }   
}
0
source

int indiv1 = Integer.parseInt(nric.charAt(1));

-1
source

All Articles