控制台程序。

公历是西方使用的日历,用GregorianCalendar类的对象来表示。GregorianCalendar对象封装了时区信息、日期和时间数据。GregorianCalendar对象有7个构造函数,默认构造函数用当前日期和时间在计算机所在的默认地点创建了日历,其他构造函数则指定了年份、月份、日期、小时、分钟和秒。默认构造函数适用于大多数情况。默认构造函数为:

GregorianCalendar calendar=new GregorianCalendar();

这个对象被设置为当前时间,调用它的getTime()方法可以把这个对象当作Date对象来访问:

Date now =calendar.getTime();

使用如下任意构造函数可以创建封装了特定日期和/或时间的GregorianCalendar对象:

GregorianCalendar(int year, int month, int day)

GregorianCalendar(int year, int month, int day, int hour, int minute)

GregorianCalendar(int year, int month, int day, int hour, int minute, int second)

day参数是月份中的天,所以值可以是1到28、29、30或31,这取决与月份以及是否为闰年。month参数的值是基于0的,所以表示一月的值是0,表示12月的值是11.

首先需要FormatInput类从键盘获得输入。

 import java.io.StreamTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException; public class FormattedInput { public int readInt() throws InvalidUserInputException {
if (readToken() != StreamTokenizer.TT_NUMBER) {
throw new InvalidUserInputException("readInt() failed." + "Input data not numeric");
} if (tokenizer.nval > (double) Integer.MAX_VALUE || tokenizer.nval < (double) Integer.MIN_VALUE) {
throw new InvalidUserInputException("readInt() failed." + "Input outside range of type int");
} if (tokenizer.nval != (double) (int) tokenizer.nval) {
throw new InvalidUserInputException("readInt() failed." + "Input not an integer");
}
return (int) tokenizer.nval;
} public double readDouble() throws InvalidUserInputException {
if (readToken() != StreamTokenizer.TT_NUMBER) {
throw new InvalidUserInputException("readDouble() failed." + "Input data not numeric");
}
return tokenizer.nval;
} public String readString() throws InvalidUserInputException {
if (readToken() == StreamTokenizer.TT_WORD || ttype == '\"' || ttype == '\"') {
return tokenizer.sval;
} else {
throw new InvalidUserInputException("readString() failed." + "Input data is not a string");
}
}
// Plus methods to read various other data types... // Helper method to read the next token
private int readToken() {
try {
ttype = tokenizer.nextToken();
return ttype; } catch (IOException e) { // Error reading in nextToken()
e.printStackTrace();
System.exit(1); // End the program
}
return 0;
} // Object to tokenize input from the standard input stream
private StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
private int ttype; // Stores the token type code
}

然后需要InvalidUserInputException类

 public class InvalidUserInputException extends Exception {
public InvalidUserInputException() { } public InvalidUserInputException(String message) {
super(message);
} private static final long serialVersionUID = 9876L; }

最后是主程序,这个例子用于推断用户出生时的重要信息。

 import java.util.GregorianCalendar;
import java.text.DateFormatSymbols;
import static java.util.Calendar.*; class TryCalendar {
public static void main(String[] args) {
FormattedInput in = new FormattedInput(); // Get the date of birth from the keyboard
int day = 0, month = 0, year = 0;
System.out.println("Enter your birth date as dd mm yyyy: ");
try {
day = in.readInt();
month = in.readInt();
year = in.readInt();
} catch(InvalidUserInputException e) {
System.out.println("Invalid input - terminating...");
System.exit(1);
} // Create birth date calendar -month is 0 to 11
GregorianCalendar birthdate = new GregorianCalendar(year, month-1,day);
GregorianCalendar today = new GregorianCalendar(); // Today's date // Create this year's birthday
GregorianCalendar birthday = new GregorianCalendar(
today.get(YEAR),
birthdate.get(MONTH),
birthdate.get(DATE)); int age = today.get(YEAR) - birthdate.get(YEAR); String[] weekdays = new DateFormatSymbols().getWeekdays(); // Get day names System.out.println("You were born on a " + weekdays[birthdate.get(DAY_OF_WEEK)]);
System.out.println("This year you " +
(birthday.after(today) ?"will be " : "are ") +
age + " years old.");
System.out.println("In " + today.get(YEAR) + " your birthday " +
(today.before(birthday)? "will be": "was") +
" on a "+ weekdays[birthday.get(DAY_OF_WEEK)] +".");
}
}

Java基础之一组有用的类——使用公历日历(TryCalendar)的更多相关文章

  1. Java基础之一组有用的类——为标记定义自己的模式(ScanString)

    控制台程序. Scanner类提供了一种方式,用来指定如何识别标记.这需要使用next()方法的两个重载版本.其中的一个版本接受Pattern类型的参数.另一个版本接受String类型的参数,用来指定 ...

  2. Java基础之一组有用的类——使用Scanner对象(TryScanner)

    控制台程序. java.util.Scanner类定义的对象使用正则表达式来扫描来自各种源的字符输入,并把输入显示为各种基本类型的一系列标记或者显示为字符串. 默认情况下,Scanner对象读取标记时 ...

  3. Java基础之一组有用的类——使用正则表达式搜索子字符串(TryRegex)

    控制台程序. 正则表达式只是一个字符串,描述了在其他字符串中搜索匹配的模式.但这不是被动地进行字符序列匹配,正则表达式其实是一个微型程序,用于一种特殊的计算机——状态机.状态机并不是真正的机器,而是软 ...

  4. Java基础之一组有用的类——生成日期和时间(TryDateFormats)

    控制台程序. java.util包中含有相当多的类涉及日期和时间,包括Date类.Calendar类和GregorianCalendar类. Date类对象其实定义了精确到毫秒的时刻,从1970年1月 ...

  5. Java基础之一组有用的类——Observable和Observer对象(Horrific)

    控制台程序. Obserable类提供了一个有趣的机制,可以把类对象中发生的改变通知给许多其他类对象. 对于可以观察的对象来说,类定义中需要使用java.util.Observable类.只需要简单地 ...

  6. Java基础之一组有用的类——使用二叉树搜索算法搜索某个作者(TryBinarySearch)

    控制台程序. Arrays类中的binarySearch()静态方法使用二叉树搜索算法,在有序数组中查找包含给定值的元素.只有当数组的元素按升序方式排序时,该方法才是最有效的,否则就应在调用binar ...

  7. Java基础之一组有用的类——使用比较器对数组排序(TrySortingWithComparator)

    控制台程序. Arrays类中的sort()静态方法把传送为参数的数组元素按升序方式排序. 对于第一个参数类型是Object[]的sort()方法来说,可以传送任意类型的数组.如果使用sort()方法 ...

  8. Java基础之一组有用的类——使用正则表达式查找和替换(SearchAndReplace)

    控制台程序. 使用正则表达式执行查找和替换操作,只需要调用Matcher对象的find()方法,就可以调用appendReplacement()方法来替换匹配的子序列.在提供给方法的新StringBu ...

  9. Java基础-类加载机制与自定义类Java类加载器(ClassLoader)

    Java基础-类加载机制与自定义类Java类加载器(ClassLoader) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 关于类加载器的概念和分类我就不再废话了,因为我在之前的笔 ...

随机推荐

  1. 免费api大全(更新中)

    免费api大全(更新中) API大全  http://www.apidq.com/    (这个碉堡了) 天气接口 气象局接口 完整数据:http://m.weather.com.cn/data/10 ...

  2. C++类型转化分析(1)

    仔细想想地位卑贱的类型转换功能(cast),其在程序设计中的地位就象goto语句一样令人鄙视.但是它还不是无法令人忍受,因为当在某些紧要的关头,类型转换还是必需的,这时它是一个必需品. 不过C风格的类 ...

  3. Segmentation

    COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION There is another way ...

  4. GenderGuesser

    http://www.hackerfactor.com/GenderGuesser.php#Analyze

  5. document.execCommand(”BackgroundImageCache”, false, true)

    很多时候我们要给一些按钮或是img设置背景,而为了达到数据与表现样式分离的效果,通常背景样式都是在CSS里设定的,但是这个行为在IE会有一 个Bug,那就是因为 IE默认情况下不缓存背景图片,所以当鼠 ...

  6. 【翻译】How To Tango With Django 1.5.4 第一章

    1.概览 这本书的目的就是为了给你提供Django实战开发的指导,这本书主要是为学生设计的,它提供了开发并运行第一个web应用程序的详细的指导步骤,并且指导你怎么将它发布到web服务器上. 本书就是为 ...

  7. 【转】android程序编译过程

    现在很多人想对Android工程的编译和打包进行自动化,比如建立每日构建系统.自动生成发布文件等等.这些都需要我们对Android工程的编译和打包有一个深入的理解,至少要知道它的每一步都做了什么,需要 ...

  8. 原因是未找到“sgen.exe”,或未安装 .NET Framework SDK v2.0

    visual studio编译出现错误:错误 2 任务失败,原因是未找到“sgen.exe”,或未安装 .NET Framework SDK v2.0.该任务正在注册表项 HKEY_LOCAL_MAC ...

  9. [LeetCode]题解(python):051-N-Queens

    题目来源 https://leetcode.com/problems/n-queens/ The n-queens puzzle is the problem of placing n queens ...

  10. Appium 已支持中文输入

    Appium 1.3.3以上. java: capabilities增加下面两项: capabilities.setCapability("unicodeKeyboard", &q ...