-3

This is my code:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int num = sc.nextInt();

    for(int i = 0; i <= num; i++){
        String calculation = sc.next();
        String b = sc.next();
        int sum = 0;

        if(calculation.equals("ADD")){
            int num2 = Integer.parseInt(b);
            int num3 = String.valueOf(Math.abs((long)num2)).charAt(0);
            int num4 = String.valueOf(Math.abs((long)num2)).charAt(1);
            int num5 = String.valueOf(Math.abs((long)num2)).charAt(2);
            int num6 = String.valueOf(Math.abs((long)num2)).charAt(3);          
            sum = num3 + num4 + num5 + num6;
        }
        System.out.println(sum - 192);
    }
}}

If the input is: 1 ADD 1234 Then the answer would be 202 instead of 10. I'm not sure where my code is wrong.

Samson Wu
  • 11
  • 2

1 Answers1

1

You are adding the ascii code of 1,2,3 and 4 all together, which is 202. Your code is all wrong:

  • It is useless to cast an int into a long and into an int again without doing operations on it.
  • If the number may be negative, then take its absolute value only once and not for each digit.
  • num2 is an int: 1234
  • String.valueOf((long)num2) is a String: "1234"
  • String.valueOf((long)num2).charAt(0) is a char: '1'

So, sum is litterally equals to '1' + '2' + '3' + '4'.

Just remove those unnecessary (and ugly) casts:

int num3 = b.charAt(0) - '0';
int num4 = b.charAt(1) - '0';
int num5 = b.charAt(2) - '0';
int num6 = b.charAt(3) - '0';          
sum = num3 + num4 + num5 + num6;

Or you can do it in one line:

sum = b.charAt(0) + b.charAt(1) + b.charAt(2) + b.charAt(3) - 4*'0';

There is probably a way to do it using lambdas as well. If you want to be a bit more secure, use a loop (a number does not always have 4 digits):

int sum = 0;
for (char c : b.toCharArray()) {
    if (c >= '0' && c <= '9') sum += c - '0';
}
T. Claverie
  • 11,380
  • 1
  • 17
  • 28
  • There are better ways to convert characters to digits - http://stackoverflow.com/questions/19388037/converting-characters-to-integers-in-java (which I believe can serve as essentially duplicate of this question) – Alexei Levenkov Jun 11 '16 at 20:56