Home > Back-end >  int array in java wont contain expected value
int array in java wont contain expected value

Time:10-31

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

CodePudding user response:

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.

CodePudding user response:

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);
}
  • Related