Reputation: 59
I have no idea of why this code snippet produces the following output when I try to multiply 2 int values. This might be too dumb but I just dont get it. I have pasted the code and the output here
public static void main(String[] args) {
// TODO code application logic here
String numstring = "12122";
char[] numArray = numstring.toCharArray();
int num =0;
int index = 10;
int count = 0;
for(int i=numArray.length-1;i>=0;i--){
int ind = (int)(Math.pow(index,count));
System.out.print(numArray[i]+"*"+ind);
System.out.println(" prints as ----->"+numArray[i]*ind);
count++;
}
}
output:
2*1 prints as ----->50
2*10 prints as ----->500
1*100 prints as ----->4900
2*1000 prints as ----->50000
1*10000 prints as ----->490000
Upvotes: 0
Views: 71
Reputation: 14699
You're not multiplying two ints. Your multiply an int
, ind, with a char
, '2'
, whose ASCII value is 50
(at least in the first case). You could use an int[]
, or if you want to stick with the char[]
, you could do the following:
System.out.println(" prints as ----->"+ Character.getNumericValue(numArray[i]) * ind);
Upvotes: 1
Reputation: 27802
Characters are really integers under the hood, so for example, the character '2' has int value 50.
To see which integer corresponds to which character, check out the ascii table.
To do what you want, you should use Character.getNumericValue() method:
System.out.println(" prints as ----->"+Character.getNumericValue(numArray[i])*ind);
Upvotes: 0