控制台程序。

公历是西方使用的日历,用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. 拦截webview调用系统浏览器打开链接

    给WebView设置自定义的WebViewClient即可 webview.setWebViewClient(new WebViewClient(){ @Override public boolean ...

  2. Java语言基础相关问题

    *动手动脑: 问题1:   仔细阅读示例: EnumTest.java,运行它,分析运行结果? 源代码: public class EnumTest { public static void main ...

  3. wordpress插入腾讯视频的方法

    wordpress插入腾讯视频的方法 最近网站需要插入腾讯视频,但是腾讯视频目前没有分享代码,只有分享到微信,qq,微博等具体选项.百度这个问题,貌似没有很好地解决办法,好像有两个插件可以使用,安装试 ...

  4. 不遗留问题-menu数据拼装

    DROP TABLE IF EXISTS `menu0910`; CREATE TABLE `menu0910` ( `id` ) NOT NULL AUTO_INCREMENT, `menu` ) ...

  5. Off-heap Memory in Apache Flink and the curious JIT compiler

    https://flink.apache.org/news/2015/09/16/off-heap-memory.html   Running data-intensive code in the J ...

  6. json格式的转换为json字符串函数

    function toJSON(object){ var type = typeof object; if ('object' == type) { if (Array == object.const ...

  7. SqlServer中的一些非常用功能

    1.启用双引号作为分隔符 Set Quoted_Identifier on 此时:create table dbo.testcolumn("column" char(2))是合法的 ...

  8. 流媒体学习一(RTP)

    一.流媒体简介 随着Internet的日益普及,在网络上传输的数据已经不再局限于文字和图形,而是逐渐向声音和视频等多媒体格式过渡.目前在网络上传输音频/视频(Audio/Video,简称A/V)等多媒 ...

  9. ExtractTablesFromSQL

    public static string[] ExtractTablesFromSQL(string cmdString) { return Regex.Matches(cmdString, @&qu ...

  10. 我的第一个WCF程序,很简单适合我等菜鸟

    1.首先我罗列一下网站搜索并经过自己理解的WCF的含义: 1)WCF:(WIndows Communication Foundation)是由微软是由微软发展的一组数据通信的应用开发接口,可以翻译为W ...