星期一, 5月 08, 2006

Hw0425

package Lab7;
import javax.swing.*;

public class Homework0425
{
private String month ;
private int day ;
private int year ;

public void setDate (int monthInt , int day , int year)
{
if (dateOK(monthInt,day,year))
{
this.day = day;
this.year = year ;
this.month = monthString(monthInt);
}
else
{
System.out.println("Fatal Error");
}
}
public void setDate(String monthString, int day, int year)
{
if (dateOK(monthString, day, year))
{
this.month = monthString;
this.day = day;
this.year = year;
}
else
{
System.out.println("Fatal Error");
System.exit(0);
}
}

public void setDate(int year)
{
setDate(1, 1, year);
}
private boolean dateOK(int monthInt, int dayInt, int yearInt)
{
return ( (monthInt >= 1) &&(monthInt <= 12) &&
(dayInt >= 1) && (dayInt <= 31) &&
(yearInt >= 1000) && (yearInt <= 9999));
}

private boolean dateOK(String monthString, int dayInt, int yearInt)
{
return (monthOK(monthString) &&
(dayInt >= 1) && (dayInt <= 31) &&
(yearInt >= 1000) && (yearInt <= 9999));
}

private boolean monthOK(String month)
{
return (month.equals("January") || month.equals("February") || month.equals("March") ||
month.equals("April") || month.equals("May") || month.equals("June") ||
month.equals("July") || month.equals("August") || month.equals("September") ||
month.equals("October") ||month.equals("November") || month.equals("December"));
}

public void writeOutput()
{
System.out.println(month +"/" + day + ", "+ year);
}


public void readInput()
{
boolean tryAgain = true ;
while (tryAgain){
String monthInput =(JOptionPane.showInputDialog("Enter a month")) ;
int dayInput = Integer.parseInt( JOptionPane.showInputDialog("Enter a day")) ;
int yearInput = Integer.parseInt(JOptionPane.showInputDialog("Enter a year")) ;
// month = monthString(monthInput);

if (dateOK(monthInput, dayInput, yearInput))
{
setDate(monthInput, dayInput, yearInput);
tryAgain = false;
}
else
System.out.println("Illegal date. Reenter input.");
}

}

public String getMonth()
{
return month ;
}

public String monthString (int monthNumber)
{
switch (monthNumber)
{
case 1:
return "Jan";
case 2:
return "Feb";
case 3:
return "Mar";
case 4:
return "Apr";
case 5:
return "May";
case 6:
return "Jun";
case 7:
return "July";
case 8:
return "Aug";
case 9:
return "Sep";
case 10:
return "Oct";
case 11:
return "Nov";
case 12:
return "Dec";
default :
System.out.println("Fatal Error") ;
System.exit(0) ;
return "Error";
}
}

}
----------------------------------------------
package Lab7;

public class Hw0425Demo {
public static void main(String[] args) {
Homework0425 date1 = new Homework0425(),
date2 = new Homework0425(),
date3 = new Homework0425();

date1.setDate(1, 2, 2008);
date2.setDate("February", 2, 2008);
date3.setDate(2008);
date1.writeOutput();
date2.writeOutput();
date3.writeOutput();
}
}
------------

0 Comments:

張貼留言

<< Home

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 Taiwan License.