Difference between revisions of "Personal Greeting"

From CompSciWiki
Jump to: navigation, search
Line 36: Line 36:
  
 
|SideSection=
 
|SideSection=
[[Image:Wiki_trays01.jpg|center]]
+
[[Image:Wiki_trays01.jpg|center;]]
 
<BR>
 
<BR>
 
Taken from http://www.flickr.com/photos/daniello/565304023/
 
Taken from http://www.flickr.com/photos/daniello/565304023/

Revision as of 12:36, 6 April 2010

Back to the Program-A-Day homepage

Problem

Write a Java program PersonalGreeting, that asks a series of questions and returns a response.
The program should:

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


Example: User inputs "Elmo" and "10" would result in something like "Welcome to COMP 1010 Elmo, you are 10 years old today."

 

...by students

center;
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

Solution

Start by importing the swing java package.

 import javax.swing.*;

Define your variables, we will need doubles in case of decimal results, and a string value for the unit

double temperature, result;
String unit;

Next start by capturing the user input using JOptionPane. We will need to use Integer.parseInt to cast the String result to an integer for the temperature.

unit = JOptionPane.showInputDialog("Enter the 1-character temperature you want to convert from c (Celcius) or f (Fahrenheit)") ;
temperature = Integer.parseInt(JOptionPane.showInputDialog("Enter the current temperature in the units you speficied"));

Now we need to use conditional statements to check for each unit, one for Celcius and one for Fahrenheit. One thing to note is that because unit is a String datatype, we will have to only extract the first character assuming it has be entered in correctly, this is easily accomplished using

unit.charAt(int index)

Where index is the position at which the char character is at in the String. For each case, calculate your results and print the output using System.out. To make your program more robust, you may want to use an else case for all invalid characters.

if (unit.charAt(0) == 'c')
{
	result = 9 * temperature / 5 + 32;
	System.out.println(temperature + " degree Celcius = " + result + " degree Fahrenheit");
}
else if (unit.charAt(0) == 'f')
{
	result = (temperature - 32) * 5 / 9;
	System.out.println(temperature + " degree Fahrenheit = " + result + " degree Celcius");
}
else
	System.out.printline("You entered an incorrect unit, please try again");

Code

Solution Code

Back to the Program-A-Day homepage