Why do I loop this result?

1
    Scanner entrada=new Scanner(System.in);

    System.out.println("Introduce un numero!");

    String tex=entrada.nextLine();

    char[] caracteres=tex.toCharArray();

    int[] numeros=new int[caracteres.length];

    for (int i=0; i<caracteres.length; i++){

        numeros[i]=caracteres[i];

        System.out.println(caracteres[i]);

        System.out.println(numeros[i]);
    }

The previous code gives me the result:

Enter a number! 123

1

49

2

50

3

51

Actually I have no idea why I get this result, basically what I want is to store the input of the user in an array of whole numbers, but in another part of the code I was giving the error that the index is out from the array, thanks in advance.

    
asked by Cokóro R1 02.02.2018 в 21:46
source

2 answers

5

The reason is simple:

The characters '1', '2' and '3' have ASCII values 49, 50 and 51, as you can see here .

When you ask Java (or C, or C ++, or C #) to do a conversion from char to int, what it really does is to extend the internal value of each character to an int (usually a char needs 1 byte)

    
answered by 02.02.2018 / 22:05
source
1

Good day, try to convert it to whole first:

numeros[i] = Integer.parseInt(caracteres[i]);
    
answered by 02.02.2018 в 21:58