rednamalas rednamalas - 11 days ago 5
Java Question

I cannot figure out why my Java code concatenates instead of adding the values

The title pretty much says it all. I'm working through the Liang java book, and I'm stuck on one of the problems. Here is my code.

/*(Sum the digits in an integer) Write a program that reads an integer between 0 and
1000 and adds all the digits in the integer. For example, if an integer is 932, the
sum of all its digits is 14.
Hint: Use the % operator to extract digits, and use the / operator to remove the
extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93.
*/

import java.util.Scanner;


public class IntegerSum{
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number to have the sum of the digits calculated: ");

int integer = input.nextInt();
int tens = integer % 10;
int hundreds = (integer / 10) % 10;
int thousands = (integer / 100);

System.out.println("The sum of the digits of the number you entered is "
+ tens + hundreds + thousands);
}
}

Answer

adding brackets should fix it. it precalculates the sum before you concatenate into the string.

System.out.println("The sum of the digits of the number you entered is "
            + (tens + hundreds + thousands));