Jeff K. Jeff K. - 25 days ago 6
Java Question

sum of numbers given date of birth in dialog box

The point of this question was to get a dialogue box open, have it ask your name and date of birth in yyyy format; then give you the sum of your date of birth digits. For example, if you were born in 1999, the program would output "X: the sum of digits in your date of birth are 28".

Here is my current code. I'm stuck on the part with computing the sum of the numbers.

import javax.swing.JOptionPane;
import java.util.Scanner;

public class Age {
public static void main(String[] args) {
String name;
String inputString;
int age;

name = JOptionPane.showInputDialog("What is " + "your name");
inputString = JOptionPane.showInputDialog("Enter the year " + "of your birth in yyyy format");

//this is where the calculations will go//

JOptionPane.showMessageDialog(null, "Hello " + name + " your age is" + inputString);
System.exit(0);
}
}

Answer Source

Another way to get this using Java 8 is:

inputString.chars()                             // get a stream of int with the char code point values
        .mapToObj(c -> (char) c)                // convert each element to its char representation
        .mapToInt(Character::getNumericValue)   // convert each char to int
        .sum();                                 // sum all elements in the stream

I would also recommend to validate the input to avoid exceptions. You can use a regex like:

if(inputString.matches("\\d{4}")){
    // do your sum
}else{
    // warn the user
}