Personal Greeting

From CompSciWiki
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.*;
import java.util.Scanner; 


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

 String name; // storage for the name
int age; // storage for the age
Scanner input = new Scanner(System.in); 


Note Note: To avoid confusion, we will assume users will enter valid input. An unfortunate disadvantage of .nextInt() is that if the user enters non numeric values the program will throw an error. You may wish to make the program more robust if you like. In a future computer science course you will learn how to handle such situations.

 System.out.print("Please enter your name: ");  
name = input.next();   
System.out.print("Please enter your age: ");
age = input.nextInt(); 
 Please enter your name: John
Please enter your  age: 19 


Now output your message .

 System.out.println("Welcome to COMP1010 "  + name + ", you are " + age + " years old today."); 
 Welcome to COMP1010 John, you are 19 years old today. 

Code

Solution Code

Back to the Program-A-Day homepage