-2

I have noticed something strange when adding two chars in a string when casting them to an integer.
For the following code I have s1 = "+1" and s2 = "+2" as input:

String s1 = scanner.next();
String s2 = scanner.next();

System.out.println(s1.charAt(1));
System.out.println((int)s1.charAt(1));

The output is:
1
49

Then I tried also the following:

Input:
+1
+2

Code:

System.out.println(s1);
System.out.println(s2);
System.out.println((int)(s1.charAt(1)) + (int)(s2.charAt(1)));

Output:
+1
+2
99

Why is it like this? Why is the output not "3" and what can I do to get it to three?

SandPiper
  • 2,816
  • 5
  • 30
  • 52
Jo An
  • 3
  • 2
  • You will find the answer here: https://stackoverflow.com/questions/17984975/convert-int-to-char-in-java (its the reverse case) – leonardkraemer Oct 21 '18 at 10:56
  • Since you know that `(int)s1.charAt(1)` is 49, and can easily find out that `(int)s2.charAt(1)` is 50, why wouldn't you expect their sum to be 99? – Andy Turner Oct 21 '18 at 11:17

3 Answers3

1

This is because when you're typecasting a character to an integer it gives you the ascii value of that character instead of converting it.

ascii value of 1 = 49 and 2 = 50 so, 49 + 50 = 99.

Instead of typecasting you should use parsing.

Integer.parseInt(s1.charAt(1)); will give you 1 instead of 49.

Try it out.

Gagan Gupta
  • 1,189
  • 7
  • 19
  • Can I correct in this case the difference by adding "-48", because I am not allowed to use type conversion methods. – Jo An Oct 21 '18 at 10:58
  • Yes, I accept it. The problem was, that I had to wait until I could, but now I can. – Jo An Oct 21 '18 at 17:20
0

The ASCII value of 1 is "49" and ASCII value fo 2 is "50", hence when you are doing s1.charAt(1)) + (int)(s2.charAt(1)), its printing "99" instead of 3.

ASCII references

Vinoth A
  • 1,099
  • 9
  • 10
0

The (int)(s1.charAt(1) return the ASCII codes 49 and 50 for character 1 and 2 respectively. So 49 + 50 = 99.

To get the integer value from an integer char use Character.getNumericValue(c). For string data, use Integer.parseInt(s).

Mean Coder
  • 304
  • 1
  • 12