2010-04-13 19 views
5

Me gustaría ingresar mi número nirc, p. S1234567I y luego poner 1234567 manera individual y como un entero como indiv1 como charAt(1), indiv2 como charAt(2), indiv como charAt(3), etc. Sin embargo, cuando se utiliza el código de abajo, me parece que no puede conseguir aún el primer número fuera? ¿Alguna idea?Java: charAt convertir a int?

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); 

Respuesta

15

que voy a recibir 49, 50, 51, etc cabo - esos son los puntos de código Unicode para '1', '2' '3', etc.

Si conocer a los personajes que van a ser cifras occidentales, que sólo puede restar '0':

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

Sin embargo, sólo se debe hacer esto después de que ya haya validado en otro lugar que la cadena tiene el formato correcto - de lo contrario' terminaré con datos falsos, por ejemplo, 'A' terminaría volviendo 17 en lugar de causar un error.

Por supuesto, una opción es tomar los valores y luego verificar que los resultados estén en el rango 0-9. Una alternativa es usar:

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

Esto devolverá -1 si el caracter no es un dígito apropiado.

No estoy seguro de si este último enfoque cubrirá dígitos no occidentales, el primero ciertamente no lo hará, pero parece que eso no será un problema en su caso.

-1

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

+1

Integer.parseInt toma una cadena, no un char. –

+0

heh oops Integer.parseInt (Character.toString (nric.charAt (1))); : P o Integer.parseInt (nric.substr (1, 1)); Pero, en serio, solo ve con la respuesta de Jon Skeet. – jonathanasdf

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

Sé pregunta es sobre char a int pero esto vale la pena mencionar porque no es negativo en la charla también))

De JavaHungry debe anotar los números negativos para el número entero si no wana utilizan caracteres.

conversión de cadena a entero: Código Pseudo

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 

StringtoInt public class {

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; 
    } 
}