|
|
Line 15: |
Line 15: |
| |Solution= | | |Solution= |
| | | |
− | |SolutionCode=<pre> | + | |SolutionCode=<pre>/* Class DaysInAMonth |
− | /* Class DaysInAMonth | + | |
| * Created by Tyler Dielschneider | | * Created by Tyler Dielschneider |
| * Made in COMP3040 | | * Made in COMP3040 |
Line 60: |
Line 59: |
| } | | } |
| } | | } |
| + | |
| </pre> | | </pre> |
| | | |
| }} | | }} |
Revision as of 14:06, 3 April 2010
Back to the Program-A-Day homepage
Problem
Create a program that allows the user to enter a month, and then outputs the number of days in that month. For simplicity sake, ask the user for the number of the month rather than the string. Also, assume there are 28 days in February. Use JOptionPane.showInputDialog to capture the input, and System.out.println to generate the output. Make sure the user enters a valid month (1-12). If they enter a number that is not in that range, output "Invalid Month". If the user enters a non-integer, let the program crash.
For example, if they want to know how many days there are in the month of January, the user would enter the number 1 and receive an answer of 31.
|
|
SideSectionTitle
Taken from http://www.flickr.com/photos/daniello/565304023/
An image or By Students section
|
Solution
|
Code
Solution Code
/* Class DaysInAMonth
* Created by Tyler Dielschneider
* Made in COMP3040
* Takes the number of a month as input and outputs the number
* of days in that month.
*/
// Need this for JOptionPane
import javax.swing.*;
public class DaysInAMonth
{
public static void main (String args[])
{
// These variables are used for input
String input;
int month;
// Get input from user
input = JOptionPane.showInputDialog(null, "Please enter a month in number format (1-12).");
// Convert string to integer
month = Integer.parseInt(input);
if( month == 1 || month == 3 || month == 5 || month == 7 ||
month == 8 || month == 10 || month == 12 ) // Months that have 31 days
{
System.out.println("This month has 31 days.");
}
else if( month == 4 || month == 6 || month == 9 || month == 11 ) // Months that have 30 days
{
System.out.println("This month has 30 days.");
}
else if( month == 2 ) // February has 28 days
{
System.out.println("This month has 28 days.");
}
else // Not a valid month
{
System.out.println("Invalid Month.");
}
}
}
|
Back to the Program-A-Day homepage