Question: Write a Java program to display a dialog box that asks you to enter your name and the year of birth as shown the first
Write a Java program to display a dialog box that asks you to enter your name and the year of birth as shown the first picture:
The program displays in a dialog box, your name and the sum of digits in your year of birth. For example, if you entered your name as PK and the year of birth as 1999, the sum of digits in the year of birth will be 1+9+9+9 = 28 and the output will be as shown the second picture:
A properly documented source code (.java files) (Do not need to add comment in each line, but you must explain the code appropriately).


The feedback said I don't have the variable "year" defined. I only have "name", also twice. So please correct and add new codes if necessary. Here, my work is
// JOptionPane to display input box and message box import javax.swing.JOptionPane;
//class declaration public class NameString {
// Main function declaration public static void main(String args[]){
// Getting name using JOptionInput box. String name = JOptionPane.showInputDialog("Enter your name.");
// Getting year using year of birth using same JOptionInput box. String name = JOptionPane.showInputDialog("Enter year of birth in yyyy format."); int sum = 0;
// Here I have initialized a variable sum to 0. This variable is used to calculate the sum. // The for loop is used to calculate the sum. Loop iterates through each digit and add it to sum. // As I have taken year in String, I first take each digit as character, covert it to string // Thenthat String is parsed to Integer form. // After converting to integer I add the integer to sum. for (int i = 0; i
// After adding integers, I have total sum of integers. // Then display the message accordingly using JOptionPane ShowMessage JOptionPane.showMessageDialog(null, name + ": The sum of digits in your year of birth is " + sum); } }
Input Enteryour name. OK Cancel Input Enter your year of birth in yyyy format. OKCancel
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
