Difference between revisions of "Personal Greeting"
Line 56: | Line 56: | ||
</pre><br/> | </pre><br/> | ||
− | Next, start by capturing the user input using [[JOptionPane_Methods#showInputDialog.28.29|JOptionPane.showInputDialog]]. We will need to use Integer.parseInt to cast the string result to an integer for the user's age. < | + | Next, start by capturing the user input using [[JOptionPane_Methods#showInputDialog.28.29|JOptionPane.showInputDialog]]. We will need to use Integer.parseInt to cast the string result to an integer for the user's age. <br/><br/> |
+ | {{note}}Note: To avoid confusion, we will assume users will enter valid input. An unfortunate disadvantage to Integer.parseInt 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. | ||
<pre> | <pre> |
Revision as of 01:04, 12 April 2010
Back to the Program-A-Day homepage
ProblemWrite a Java program PersonalGreeting, that asks a series of questions and returns a response.
|
Mid-term Review | |
---|---|---|
SolutionStart 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 |