Jeff K. Jeff K. - 6 months ago 33
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);

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:

    // do your sum
    // warn the user
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download