Personal Greeting

From CompSciWiki
Revision as of 14:23, 9 April 2010 by TimC (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Write a Java program PersonalGreeting, that asks a series of questions and returns a response.
For all input and output use JOptionPane to help review the first chapter's material.

Your program should do the following:

  • prompt the user for their name
  • prompt the user for their age
  • output a greeting message that displays both name and age gathered from the input


This program will cover the following topics:



Example: If a user inputs "Elmo" for their name and "10" for their age, then the result would look something like "Welcome to COMP 1010 Elmo, you are 10 years old today."

 

Mid-term Review

Wiki trays01.jpg

Solution

Start by importing the swing java package. We need this to make calls to the JOptionPane class.

 import javax.swing.*;

Define your variables, we will need a String for your name and an int for age.

//local variables
String name;
int age;

Next, start by capturing the user input using JOptionPane.showInputDialog. We will need to use Integer.parseInt to cast the string result to an integer for the user's age.

//input
name = JOptionPane.showInputDialog("Please enter your name") ;
age = Integer.parseInt(JOptionPane.showInputDialog("Please enter your age"));

Now output your message using JOptionPage.showMessageDialog. Make sure first parameter is null. Don't forget to use the + operator when appending strings (sometimes referred to as concatenation).

//output
JOptionPane.showMessageDialog(null, "Welcome to COMP1010 "  + name + ", you are " + age + " years old today.");

Code

Solution Code

Back to the Program-A-Day homepage