简体   繁体   中英

int array in java wont contain expected value

I want that my array num cosist of each char from my string b like this:

num[0] = 9;
num[1] = 1;
num[2] = 1;
num[3] = 9;

but somehow the 9 turns into a 57 and the 1 turns into 1. I dont get why. When i print out b.charAt(i) the numbers are correct but as soon as i try to initialze the array the numbers change. I also tried to cast with (int)b.charAt(i) but that didnt make a difference. why do the numbers change ?

int a = 9119;
String b = a+"";
System.out.println(b);
int [] num = new int[b.length()];
String c = "";

for (int i = 0; i < b.length(); i++)
{
    System.out.println(b.charAt(i));
    num[i] = b.charAt(i);
    //c += (num[i] * num[i])+"";System.out.println(c);
}
for (int w : num)
{
    System.out.println(w);
}

this is the console outprint:

9119
9
1
1
9
57
49
49
57

With the line num[i] = b.charAt(i); you are basically converting the character 9 to its decimal representation, which is 57 . The same is true for 1 which decimal representation is 49 .

If you turn your int[] num into char[] num everything works as expected. Additionally, use String.valueOf() to convert an int into a String :

int a = 9119;
String b = String.valueOf(a);
System.out.println(b);
char[] num = new char[b.length()];

for (int i = 0; i < b.length(); i++) {
    System.out.println(b.charAt(i));
    num[i] = b.charAt(i);
}

for (char w : num) {
    System.out.println(w);
}

note that the char '9' is different from the int 9,

char a = '9'; int b = a;

for code like this, it will auto-cast the char '9' into int by the ASCII code of the letter '9', in the ASCII table, '9' is the 57th letter, so the auto-cast will let our int b assigned to the value 57. similar idea for char '1', int ASCII table, the number is 49.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM