Sum of integers within a string?

Viewed 86
    System.out.println("nums:");
    String values = myScanner.nextLine();
    int count = 0;
    int sum = 0;
    for (int i = 0; i < values.length(); i++){
        if (values.charAt(i) != ' '){
            char num = values.charAt(i); 
            int val = num;
            sum += val;
        }   
    }
    System.out.println(sum); 
  }
}
  • Input is "1 2 3" and simply trying to compute sum. However it returns 150 instead of 6
6 Answers

You are adding ASCII values instead of the integer. Need to parse them first. Evne so your code only deal with 1-digit integers

The character code of a digit is not equal to the value represented by that digit.

You're adding up character codes.

Firstly, you need to decide whether you mean "integers" (per title) or "digits" (per attempt at code). Is "12 12" supposed to be 6 (1 + 2 + 1 + 2) or 24 (12 + 12)?

Then you need to convert strings of characters, or single characters (depending on answer to preceding decision) to integer values.

You can get the numeric value of a char, by subtracting the char '0'

e.g. 

    char one = '1';
    int intOne = one - '0';

You need to convert the integer to an actual int using Integer.parseInt()

System.out.println("nums:");
Scanner myScanner = new Scanner(System.in);
String values = myScanner.nextLine();
int count = 0;
int sum = 0;
for (String s : values.split("\\s+")) {
    sum+= Integer.parseInt(s);
}
System.out.println(sum);

Prints

6

Assuming you had a string or digits, you could also do it like this.

String str = "12345";
int sum = 0;
for (char c : str.toCharArray()) {
   // convert the ascii value to a usable int, then add it to the sum
   sum = sum * 10 + c - '0';
}
System.out.println(sum);

Prints

12345

Why does the previous solution work? Characters are encoded in different ways to be printed. Characters 0 thru 9 are ASCII encoded (in decimal) as 48, 49, 50, 51 ... So when you added 1, 2, and 3 you really added 49, 50, and 51 and obtained 150. So you need to subtract '0' or 48 from each character digit to get the actual binary value that it represents. Above, I just multiplied each time by 10 to move the current value left to make room for the next digit.

0     * 10 + 1 = 1
1     * 10 + 2 = 12
12    * 10 + 3 = 123
123   * 10 + 4 = 1234
1234  * 10 + 5 = 12345
    int sum = 0;
    for (int i = 0; i < values.length(); i++) {
        char c = values.charAt(i);
        if (c >= '0' && c <= '9') {
            sum = sum + (c - '0');
        }
    }

Explain:

  • c >= '0' && c <= '9' : to make sure that we only make the sum of numeric character
  • c - '0': returns the difference of the index in the ascii table.

enter image description here

There are two problems with your approach:

  1. You are adding the char values directly and therefore their ASCII values are getting added to sum. The ASCII value of '0' is 48, that of '1' is 49, that of '2' is 50 and so on. So, '1' + '2' + '3' = 49 + 50 + 51 = 150. What you need is 1 + 2 + 3 which you can get in one of the following ways:
    • Subtract '0' from the char e.g. '1' - '0' = 49 - 48 = 1.
    • Use Character#getNumericValue e.g. Character.getNumericValue('1') gives you 1.
  2. You are getting the numbers from the string using charAt(i) which will give you a wrong result if you have numbers of two or more digits e.g. 15 2 20. So, assuming that you fix the problem mentioned in the point#1 above, it will give you 1 + 5 + 2 + 2 + 0 = 10, not 37 which you might be expecting. In order to fix this problem, you should split the string on whitespace and convert them into int using Integer#parseInt.

Given below is the code incorporating these comments:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        System.out.println("nums:");
        String values = myScanner.nextLine();
        int sum = 0;
        for (String num : values.split("\\s+")) {
            sum += Integer.parseInt(num);
        }
        System.out.println(sum);
    }
}

A sample run:

nums:
1 2 3
6

Uisng Stream API:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        System.out.println("nums:");
        String values = myScanner.nextLine();
        int sum = Arrays.stream(values.split("\\s+")).mapToInt(Integer::parseInt).sum();
        System.out.println(sum);
    }
}
Related