java homework 2

Assignment

Part 1: Command Oriented Personal Information Manager

This assignment involves the creation of simple Personal Information Management system that can deal with 4 kinds of items: todo items, notes, appointments and contacts. Each of these kinds of items is described in more detail below. The assignment requires that you create a class for each item type, and that each class extends an abstract base class provided for you. In addition to creating the four classes, you need to create a manager class that supports some simple text-based commands for creating and managing items.

Each of your 4 item type classes will be derived from the following abstract class:

public abstract class PIMEntity {

String Priority; // every kind of item has a priority

// default constructor sets priority to "normal"

PIMEntity() {

Priority = "normal";

}

// priority can be established via this constructor.

PIMEntity(String priority) {

Priority =  priority;

}

// accessor method for getting the priority string

public String getPriority() {

return Priority;

}

// method that changes the priority string

public void setPriority(String p) {

Priority = p;

}

// Each PIMEntity needs to be able to set all state information

// (fields) from a single text string.

abstract public void fromString(String s);

// This is actually already defined by the super class

// Object, but redefined here as abstract to make sure

// that derived classes actually implement it

abstract public String toString();

}

PIMTodo

Todo items must be PIMEntites defined in a class namedPIMTodo. Each todo item must have a priority (a string), a date and a string that contains the actual text of the todo item.

PIMNote

Note items must be PIMEntites defined in a class namedPIMNote. Each note item must have a priority (a string), and a string that contains the actual text of the note.

PIMAppointment

Appointment items must be PIMEntites defined in a class namedPIMAppointment. Each appointment must have a priority (a string), a date and a description (a string).

PIMContact

Contact items must be PIMEntites defined in a class namedPIMContact. Each contact item must have a priority (a string), and strings for each of the following: first name, last name, email address.

There is one additional requirement on the implementation of the 4 item classes listed above, the 2 classes that involve a date must share aninterfacethat you define. You must formally create this interface and have both PIMAppointment and PIMTodo implement this interface.

PIMManager

You must also create a class namedPIMManagerthat includes amainand provides some way of creating and managing items (from the terminal). You must support the following commands (functionality):

List:print a list of all PIM items

Create:add a new item

Save:save the entire list of items (HW2: simple version, just print out; complex version, to a file, should be finished after I/O topic, to database, can (optional) be finished after JDBC topic, to a remote server, can (optional) be after Networking topic. )

Load:read a list of items from a file

When creating a new item it is expected that the user must response to a sequence of prompts to enter the appropriate information (and even to indicate what kind of item is being created). Do this any way you want, just make sure that your system provides enough information (instructions) so that we can use your systems!

There is no required format for the user interface, anything that allows users to create, list, save and load is fine. Here is what it might look like (user input shown in red):

java PIMManager

Welcome to PIM.

---Enter a command (suported commands are List Create Save Load Quit)---

List

There are 0 items.

---Enter a command (suported commands are List Create Save Load Quit)---CreateEnter an item type ( todo, note, contact or appointment )

todo

Enter date for todo item:

03/25/2013

Enter todo text:Submit java homework.

Enter todo priority:

urgent

---Enter a command (suported commands are List Create Save Load Quit)---

List

There are 1 items.

Item 1: TODO urgent 03/25/2013 Submit Java homework.

---Enter a command (suported commands are List Create Save Load Quit)---

Save

Items have been saved.

---Enter a command (suported commands are List Create Save Load Quit)---

Quit

Note that there is not a required Delete command. Feel free to use any data structure you want to hold a list of items, you are allowed to use a simple array with size 100 (you are not required to support lists of more than 100 items). Handling array bound exception is required.

Alternative PIMEntity

ReimpletementPIMEntityasinterface, add change the rest of all code to use it.

mycode:

import java.util.Scanner;

import java.io.*;

interface Date{

void setDate(String d);

}

class PIMTodo extends PIMEntity implements Date{

String date,todoText;

public PIMTodo(){

}

public void setDate(String d){

date=d;

}

void setTodoText(String todo){

todoText=todo;

}

public void fromString(String s){

}

public String toString(){

return ("Item "+PIMManager.itemno+": TODO "+Priority+" "+date+" "+todoText+".");

}

}

class PIMNote extends PIMEntity{

String noteText;

void setNoteText(String n){

noteText=n;

}

@Override

public void fromString(String s) {

// TODO Auto-generated method stub

}

@Override

public String toString() {

// TODO Auto-generated method stub

return ("Item "+PIMManager.itemno+": NOTE "+Priority+" "+noteText+".");

}

}

class PIMAppointment extends PIMEntity implements Date{

String date,description;

public void setDate(String d){

date=d;

}

void setDescription(String des){

description=des;

}

@Override

public void fromString(String s) {

// TODO Auto-generated method stub

}

@Override

public String toString() {

// TODO Auto-generated method stub

return ("Item "+PIMManager.itemno+": APPOINTMENT "+Priority+" "+date+" "+description+".");

}

}

class PIMContact extends PIMEntity{

String firstname,lastname,email;

void setFirstname(String f){

firstname = f;

}

void setLastname(String l){

lastname = l;

}

void setEmail(String e){

email = e;

}

@Override

public void fromString(String s) {

// TODO Auto-generated method stub

}

@Override

public String toString() {

// TODO Auto-generated method stub

return ("Item "+PIMManager.itemno+": CONTACT "+Priority+" "+firstname+" "+lastname+" "+email+".");

}

}

public class PIMManager {

static int itemno=0;

static String[] List=new String[100];

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

System.out.println("Welcome to PIM.");

Scanner in = new Scanner(System.in);

OUT:

while(true){

System.out.println("---Enter a command (supported commands are List Create Save Load Quit)---");

String input = in.next();

switch(input){

case "List":

System.out.println("There are "+itemno+" items.");

for(int i=1;i<=itemno;i++){

if(itemno==0) break;

System.out.println(List[i]);

}

break;

case "Create":

System.out.println("Enter an item type(todo,note,contact,appointment)");

input=in.next();

switch(input){

case "todo":

PIMTodo todo=new PIMTodo();

System.out.println("Enter date for todo item:");

BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));

input=buff.readLine();

todo.setDate(input);

System.out.println("Enter todo text:");

BufferedReader buff1=new BufferedReader(new InputStreamReader(System.in));

input=buff1.readLine();

todo.setTodoText(input);

System.out.println("Enter todo priority:");

BufferedReader buff2=new BufferedReader(new InputStreamReader(System.in));

input=buff2.readLine();

todo.setPriority(input);

//start with 1(zero is not used)

itemno++;

String r=todo.toString();

List[itemno]=r;

break;

case "note":

PIMNote note=new PIMNote();

System.out.println("Enter note text:");

BufferedReader buff3=new BufferedReader(new InputStreamReader(System.in));

input=buff3.readLine();

note.setNoteText(input);

System.out.println("Enter note priority:");

input=in.next();

note.setPriority(input);

itemno++;

String r1=note.toString();

List[itemno]=r1;

break;

case "contact":

PIMContact contact=new PIMContact();

System.out.println("Enter firstname for contact item:");

BufferedReader buff4=new BufferedReader(new InputStreamReader(System.in));

input=buff4.readLine();

contact.setFirstname(input);

System.out.println("Enter lastname for contact item:");

BufferedReader buff5=new BufferedReader(new InputStreamReader(System.in));

input=buff5.readLine();

contact.setLastname(input);

System.out.println("Enter email for contact item:");

BufferedReader buff6=new BufferedReader(new InputStreamReader(System.in));

input=buff6.readLine();

contact.setEmail(input);

System.out.println("Enter contact priority:");

input=in.next();

contact.setPriority(input);

itemno++;

String r2=contact.toString();

List[itemno]=r2;

break;

case "appointment":

PIMAppointment appointment=new PIMAppointment();

System.out.println("Enter date for appointment item:");

BufferedReader buff7=new BufferedReader(new InputStreamReader(System.in));

input=buff7.readLine();

appointment.setDate(input);

System.out.println("Enter appointment description:");

BufferedReader buff8=new BufferedReader(new InputStreamReader(System.in));

input=buff8.readLine();

appointment.setDescription(input);

System.out.println("Enter appointment priority:");

input=in.next();

appointment.setPriority(input);

itemno++;

String r3=appointment.toString();

List[itemno]=r3;

break;

default:

System.out.println("the item type is not exist");

break;

}

break;

case "Save":

System.out.println("Item have been saved.");

break;

case "Quit":

in.close();

break OUT;

default:

System.out.println("the command is not exist");

break;

}

}

}

}


代码虽多,但是模式是一样的,都是从继承题目给定class PIMEntity。

使用了一个class Scanner:

Scanner in = new Scanner(System.in);

从键盘输入放到Scanner里,通过in.next()来获得键入的字符,但是如果键入的参数列表用空格隔开,它会认为是多个参数。所以如果想键入的单个参数可以用空格隔开的话,可以用:

BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));

input=buff.readLine();

但它的缺点是每次使用的时候都要重新new一下,就是要创建新对象,而且每次都要不一样。就是你想输入多少个,你就创建多少个对象缓冲区。

Assignment

Part 2: Class Substring

Create a class namedSubstringthat will expect the first command line argument to be a string, and the second two command line arguments to be integers, the first will be used as an index and the second as a length. The output should be the subtring of string starting at the index and of the specified length. Examples:

> java Substring Jello 1 3

ell

> java Substring "Hello World" 0 5

Hello

> java Substring OneTwoThree 5 1

o

Notes:As you can see from the examples, an index of 0 refers to the first character in the string. To figure out how to extract a substring from a String, check out the API documentation for the class String which can be found injava.lang

my code:

public class Substring {

Substring(char[] c,int start,int length){

String s=new String();

for(int i=start;i<start+length;i++){

s=s+c[i];

}

System.out.print(s);

}

static char[] c;

static int i=0;

static int start,length;

@SuppressWarnings("unused")

public static void main(String[] args) {

// TODO Auto-generated method stub

for(String s:args){

if(i==0){

c=s.toCharArray();

}else if(i==1){

start=Integer.parseInt(s);

}else if (i==2){

length=Integer.parseInt(s);

}

i++;

}

Substring sub=new Substring(c,start,length);

}

}

another:

public class Substring{

public static void main(String[] args){

int i=Integer.parseInt(args[1]);

int j=Integer.parseInt(args[2]);

System.out.print(args[0].substring(i,i+j));

}

}

很简单的一道题,第一个实现用了toCharArray()这个函数,第二个实现用了substring()这个函数。

Assignment

Part 3: Calendar generating program

Write a java program named cal (the main() should be in a class named "cal") that will print out to standard output the calendar for any month. Your program should look at the command line arguments for a numeric month and year, and print the calendar for that month in the format displayed below. If there are no command line arguments, or if the command line arguments are not a valid month and year, your program must print the calendar for the current month. This program is a java version of the Unix "cal" command. Sample usage of your program is shown below:

> java cal

March 2013

Su Mo Tu We Th Fr Sa

                           1  2

  3    4   5  6   7   8  9

10 11 12 13 14 15 16

17 18 19 20 21 22 23

24 25 26 27 28 29 30

31

> java cal 4 2025

April 2025

Su Mo Tu We Th Fr Sa

              1  2  3   4  5

 6   7   8   9  10  11 12

13 14 15 16 17 18 19

20 21 22 23 24 25 26

27 28 29 30

As the above examples show, the program should print out the month and year, followed by the days of the week (using the same abbreviation as shown above) and the dates in the month. Your program must produce a tabular output exactly like the above examples, the only difference should be the exact position of the dates (which depend on the specific month asked for). It is required that the columns of the calendar line up just like the above examples!

Notes:

You probably want to use a java.util.Calendar object!

my code:

import java.util.*;

public class cal {

static int daysInMonth( Calendar c) {

return(c.getActualMaximum(Calendar.DAY_OF_MONTH));

}

static String dayName( Calendar c) {

// Need to subtract 1, since the first DAY_OF_WEEK is 1 !

return(DAYS[c.get(Calendar.DAY_OF_WEEK)-1]);

}

static String monthName(Calendar c) {

return(MONTHS[c.get(Calendar.MONTH)]);

}

cal(int month,int year){

Calendar c = Calendar.getInstance();

//clear is important

c.clear();

c.set(Calendar.YEAR,year);

c.set(Calendar.MONTH,month);

int day=daysInMonth(c);

// c.set(Calendar.DATE,1);

// c.roll(Calendar.DATE,-1);

// int day=c.get(Calendar.DATE);

int b=c.get(Calendar.DAY_OF_WEEK);

String mn=monthName(c);

System.out.println(mn+" "+year);

System.out.println("Su Mo Tu We Th Fr Sa");

for(int i=1;i<b;i++){

System.out.print("  ");

}

for(int i=1;i<=day;i++){

if (i<10){

System.out.print(" "+i+" ");

}else{

System.out.print(i+" ");

}

if(b==7){

System.out.println();

b=1;

}else{

b++;

}

}

}

static final String[] DAYS ={ "Sunday",

"Monday",

"Tuesday",

"Wednesday",

"Thursday",

"Friday",

"Saturday" };

static final String[] MONTHS = { "January",

"February",

"March",

"April",

"May",

"June",

"July",

"August",

"September",

"October",

"November",

"December"};

static int i=0;

@SuppressWarnings("unused")

public static void main(String[] args) {

// TODO Auto-generated method stub

Calendar c=Calendar.getInstance();

for (String s:args ) {

i++;

}

if(i==0){

int month=c.get(Calendar.MONTH);

int year=c.get(Calendar.YEAR);

cal calendar=new cal(month,year);

}else{

int month = Integer.parseInt(args[0])-1;

int year = Integer.parseInt(args[1]);

cal calendar=new cal(month,year);

}

}

}


这个题目就是让我们了解一下class Calendar。

Calendar c = Calendar.getInstance();

返回当前的时间

经常用的set(),get()方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,189评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,577评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,857评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,703评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,705评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,620评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,995评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,656评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,898评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,639评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,720评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,395评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,982评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,953评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,195评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,907评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,472评论 2 342

推荐阅读更多精彩内容