Reputation: 11
I am trying to add four integers ie 4+3+2+1 but i get the value 202
class Task3{
public static void main (String args[]){
String x=(args[0]);
int I = Integer.parseInt (x);
char c1 = x.charAt(0);
char c2 = x.charAt(1);
char c3 = x.charAt(2);
char c4 = x.charAt(3);
System.out.println("First and last digit is: " + c1 +"," + c4);
if (c1 > c4)
System.out.println("The first digit is larger");
else
System.out.println("The second digit is larger");
int sum = c1 + c2 + c3 + c4;
System.out.println(sum);
}
}
Upvotes: 0
Views: 922
Reputation: 1
I presume you are passing "4321" or similar to the program.
c1 will not be the number 1 but actually the Unicode number representing the character '1' which is actually 31 (in hexadecimal). The latest addition is adding these Unicode numbers.
See http://unicode-table.com/en/ for the list of unicode numbers to characters and also http://docs.oracle.com/javase/tutorial/i18n/text/unicode.html for more details of characters in Java.
Upvotes: 0
Reputation: 8946
The reason of the wrong output others already explained it now one of the way to get the correct output
int sum =0;
while(I>0){
int rem = I%10;
sum+=rem;
I = I/10;
}
System.out.println(sum);
Upvotes: 1
Reputation: 16354
You are trying to sum up the char
s ASCII codes and not the digit values. You have to retrieve the corresponding digit for each character and then evaluate you addition result:
class Task3
{
public static void main (String args[])
{
String x=(args[0]);
int I = Integer.parseInt (x);
char c1 = x.charAt(0);
char c2 = x.charAt(1);
char c3 = x.charAt(2);
char c4 = x.charAt(3);
int i1 = Character.digit(c1, 10);
int i2 = Character.digit(c2, 10);
int i3 = Character.digit(c3, 10);
int i4 = Character.digit(c4, 10);
System.out.println("First and last digit is: " + i1 +"," + i4);
if (i1 > i4)
System.out.println("The first digit is larger");
else
System.out.println("The second digit is larger");
int sum = i1 + i2 + i3 + i4;
System.out.println(sum);
}
}
Upvotes: 2
Reputation: 7118
Change
int sum = c1 + c2 + c3 + c4;
to
int sum = c1 + c2 + c3 + c4 - 4 * '0';
Since c1, c2, c3, c4 are all characters, so a digit say. 4 is taken as '4' that is basically the ASCII value, so to get 4 and not '4' you need to subtract '0' from each of c1, c2, c3, c4, so 4 * '0' subtracted
Upvotes: 2
Reputation: 3281
replace char c1 = x.charAt(0);
with Character.getNumericValue(x.charAt(0))
Upvotes: 2
Reputation: 726539
This is because you are adding numeric values of UNICODE code points, not digits represented by the corresponding characters.
In order to get a digit from a character code, call Character.digit(c1, 10)
(ten indicates that you want a decimal digit).
int c1 = Character.digit(x.charAt(0), 10);
int c2 = Character.digit(x.charAt(1), 10);
int c3 = Character.digit(x.charAt(2), 10);
int c4 = Character.digit(x.charAt(3), 10);
Upvotes: 2