CSC-140 Assignment 6

Similar documents
Handout 7. Defining Classes part 1. Instance variables and instance methods.

CSC-140 Assignment 5

Programming Assignment #2

CSC 172 Intermediate Progamming

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

CMSC 132, Object-Oriented Programming II Summer Lecture 5:

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Variables, Data Types, and Arithmetic Expressions Learning Objectives:

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSC-140 Assignment 4

TOP-DOWN PROCEDURAL PROGRAMMING

Timing for Interfaces and Abstract Classes

UNIT TESTING. Krysta Yousoufian CSE 331 Section April 19, With material from Marty Stepp, David Notkin, and The Pragmatic Programmer

Tips from the experts: How to waste a lot of time on this assignment

COMP 250 Winter 2011 Reading: Java background January 5, 2011

CIS 190: C/C++ Programming. Classes in C++

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

COSC 1010 Introduction to Computer Programming

CSEN 202: Introduction to Computer Programming Spring term Final Exam

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

C# Programming for Developers Course Labs Contents

Lab Assignment Three

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Scheduling. Scheduling Tasks At Creation Time CHAPTER

Announcements. 1. Forms to return today after class:

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Abstract Data Types. Different Views of Data:

Chapter 1 Getting Started

Enumerated Types. CSE 114, Computer Science 1 Stony Brook University

Topic 4 Expressions and variables

APCS Semester #1 Final Exam Practice Problems

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Topic 5: Enumerated Types and Switch Statements

COP 3330 Final Exam Review

MIT AITI Python Software Development

Claremont McKenna College Computer Science

Java and OOP. Part 2 Classes and objects

Getting started with Java

CS 116. Lab Assignment # 1 1

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

Cloning Enums. Cloning and Enums BIU OOP

CSE 113 A. Announcements - Lab

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Controls Structure for Repetition

CONDITIONAL EXECUTION: PART 2

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

Rules and syntax for inheritance. The boring stuff

CS 113 PRACTICE FINAL

If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider:

AQA Decision 1 Algorithms. Section 1: Communicating an algorithm

Compiler Design Spring 2017

Advanced Java Concepts Unit 3: Stacks and Queues

HW3: CS 110X C Domain Information. Final Version: 1/29/2014

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Operator overloading: extra examples

Final Exam Practice. Partial credit will be awarded.

CHAPTER 7 OBJECTS AND CLASSES

Classes Classes 2 / 36

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Classes Classes 2 / 35

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Computer Science II (20082) Week 1: Review and Inheritance

Example. Section: PS 709 Examples of Calculations of Reduced Hours of Work Last Revised: February 2017 Last Reviewed: February 2017 Next Review:

Options for User Input

Operational Semantics. One-Slide Summary. Lecture Outline

ACORN.COM CS 1110 SPRING 2012: ASSIGNMENT A1

Letterkenny Institute of Technology

JAVA OPERATORS GENERAL

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Chapter 6 Lab Classes and Objects

CSC 240 Computer Science III Spring 2018 Midterm Exam. Name

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

public static boolean isoutside(int min, int max, int value)

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

CIS 162 Project 4 Farkle (a dice game)

Read and fill in this page now. Your lab section day and time: Name of the person sitting to your left: Name of the person sitting to your right:

Java Identifiers, Data Types & Variables

Programming Language Concepts: Lecture 2

Java Foundations. 7-2 Instantiating Objects. Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Programming Languages and Techniques (CIS120)

CSE 351: The Hardware/Software Interface. Section 2 Integer representations, two s complement, and bitwise operators

Equality for Abstract Data Types

if Statement Numeric Rela5onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

CS 302 Week 9. Jim Williams

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

if Statement Numeric Rela7onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I

Programming Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science Indian Institute of Technology, Madras

Helping You C What You Can Do with SAS

CSCE 156 Computer Science II

Sample First Midterm Exam The Answers

Transcription:

CSC-140 Assignment 6 1 Introduction In this assignment we will start out defining our own classes. For now, we will design a class that represents a date, e.g., Tuesday, March 15, 2011, or in short hand notation: 03/15/2011. Before we specify the requirements for the class, let us just recap the important things we have learned about fields, methods and modifiers. 1.1 Modifiers Let us briefly recap the modifiers public, private, static, and final. Let us start from the back. 1.1.1 The Final Modifier If the final modifier is used with a field, it means that the field cannot be re-defined in any subclass (we haven t talked about subclasses yet, so don t worry about that), but the final modifier is also used when we wanted to declare someting as a constant (typically together with the modifier static.) The final modifier with a method means that it cannot be re-implemented in any subclasses of the class. (Again, don t worry about that for now.) 1.1.2 The Static Modifier The static modifier is very important - please make sure you understand it 100%. If a field is declared static, only one instance of it exists, namely in the class in which it was declared. If a field is not static, each object created based on the class will have its own copy of the field. If a method is static, it can only operate on its parameters, locals and any static fields. It is important to understand why a static method cannot access non-static fields: A non-static field is associated with an object; a static method is associated with a class (just like a static field). 1

A static method f in a class A can be invoked as: A.f(), which means that there will be no object context, i.e., all non-static fields won t be accessible because they live in objects, but no objects are present. 1.1.3 The Public and Private Modifiers The public modifier used with a field (field) allows anyone holding a reference to the object (o), in which the field was declared, to access it through o.field. If the field is static it can further more be accessed though the class in the same manner. The same is true for methods. If the private modifier is used with a field, only object of the same class may access these fields. The same is true for methods. 2 The Date Class We wish to write a public class called Date. It should be placed in a file called Date.java. It should have three private fields: one to represent the day, one for the month, and one for the year. You can use int as a type. Further more, 2 constant String arrays (private, static and final, one called days with the names of the weekdays, starting at Sunday, and one called months with the names of the months, starting at January. Question 1: compiles. Implement this class with the 5 fields, and make sure it 2.1 Constructors and Factory Methods Naturally a class like Date should have a constructor that takes in three parameters: day, month, and year, and transfers them to the fields. Remember, if a field and a parameter is called the same, the field (if it is non-static) can be referenced by prefixing this. (this and a dot. ). However, what happens if we instantiate the class like this: newdate(15, 34, 4576); There is no 34th day in the non-existing 15th month, and the year cannot be negative, we would get a strange object representing a non-existing date. 2

However, we still need a constructor, but if we make it private, it cannot be invoked from outside the class. Now, how do we instantiate a class if there is no constructor? We can make a static method called makedate that takes in the day, month and year, and then before instantiating the Date class using the private constructor, it validates the date. The code for makedate is here: public static Date makedate(int day, int month, int year) { if (validdate(day,month, year)) return new Date(day, month, year); else return null; } If the validdate call returns false, no object is constructed, and the null value is returned. If the date is valid, we instantiate the object through the private constructor, and return the newly created object. Outside the class we could have code that looks something like this: Date da = Date.makeDate(12,31,2011); if (da!= null) // do something with it Your next task is to write the static method validdate used in the code snippet above, but even before that we need another private, static helper method called isleapyear, that takes in an integer parameter, representing a year, and returns a boolean value: true if the year is a leap year, false otherwise. A year is a leap year if it is divisible by 4 (i.e., the remainder when dividing by 4 is 0), unless it is divisible by 100 (the it is not a leap year, so 1900 was not a leap year), unless divisible by 400, because then it is a leap year (2000 is divisible by 4, and 100 but also by 400, so it is a leap year). No we can write validdate with the following interface: public static boolean validdate(int day, int month, int year) according to the following specification: 3

validdate should return true if all of the following consitions are met: The year should be greater than or equal to 1500 and smaller than or equal to 3000. The month should be greater than or equal to 1 (representing January) and smaller than or equal to 12 (representing December). The day should be greater than or equal to 1 and if the month is 1,3,5,7,8,10, or 12, smaller than or equal to 31; if the month is 4,6,9, or 11, day should be smaller than or equal to 30, and if the month is 2 (representing February, it should be smaller than or equal to 28 unless the year is a leap year, then it could be a large as 29. Question 2: Implement isleapyear Question 3: Implement isvaliddate Question 4: Implement makedate as it is shown above as well as the private constructor 2.2 Turning Objects in to Strings Java allows the author of a class to implement a special public method called tostring(); it takes no parameters and returns a String. This method is automatically invoked when a variable holding a reference to an object is used in an expression of String type. E.g. If da is a reference to an object of Date type, then String s = "Today s date is " + da; is the same as: String s = "Today s date is " + da.tostring(); Implement tostring() for the Date class such that the string returned is mm/dd/yyyy, where mm is the month, dd is the day, and yyyy is the year. Make sure that if the month and/or the day is less than 10 (i.e., does not 4

take up 2 spaces), that you pad an extra "0" on there. For example, January 7th, 2002 should be 01/07/2002. Question 5: Implement the tostring() method. 2.3 Printing a Fancy Date We can use the value of the month field as an index into the months array to get a textual representation of the month, but if we want to know the weekday, we need to do a little arithmetic. In the following, day, month, and year refer to the fields of a Date object. The value in the variable d will be the index into the days array. All the arithmetic is integer arithmetic. a = 14 month 12 y = year a m = month + 12 a 2 d = (day + y + y 4 y 100 + y 400 + 31 m 12 ) % 7 Question 6: Implement a public method called getfancydate() that returns a string (appropriate for the date represented by the object), that looks like this: Friday, January 7, 2011. 2.4 Comparing Dates You must write a public method called isearlier that takes in another Date object, and return a boolean. false should be returned if the parameter object represents an earlier date than the object on which the method was invoked. For example: Date d1 = Date.makeDate(1,3,2010); Date d2 = Date.makeDate(10,5,2011); boolean b1 = d1.isealier(d2); boolean b2 = d2.isealier(d1); would leave the value true in b1 and false in b2. Since the parameter is of the same type as the object to which it is passed (called the target object), the target object could access the private fields 5

though objref.fieldname, e.g., d2.year, but it isn t a very nice way to do it. Also, if someone else is holding a reference to a Date object and would like to know the day, there is no way to gain access to the day field as it is private to the object, and thus cannot accessed as objref.fieldname. Therefore, the class should have accessor methods that return the values of the various data fields. E.g. We can write a public method called getday() that returns the day field like this: public int getday() { return day; } Question 7: Implement getday(), getmonth(), and getyear()/ Question 8: Implement isealier(date d2). 3 Topics Covered Modifiers (static, public, private, final). Fields. Methods. Constructors / factory methods. Converting Objects to strings. 4 Work List 1. Make sure you read the Topics Covered section and familiarize yourself with all the topics. 2. Create a file Date.java, and implement the code from the questions above. 3. Create a file DateTest.java (you can see an example of one at the end of this handout) to test your code in. 6

4. Test your program with a number of different values. 5. Once you are happy with your solution, type the following: tar -cvf Assignment6.tar Date.java DateTest.java to create a.tar file that you can then go to csgfms.cs.unlv.edu and hand it in. If you don t name your two files Date.java and DateTest.java the tar command will fail. 6. Bring to class (along with the printout of your solution) a write up in which you explain how you solved the problem, and show output from a couple of tests; enough to convince me that it works. 5 Due Date The Assignment6.tar file must be uploaded to csgfms.cs.unlv.edu no later than Monday April 4th before midnight (midnight between Monday and Tuesday), and the write up should be brought to class the day after. 7

6 Sample Output from my Solution Invalid Date. d1 = 05/01/2003 d2 = 07/05/2001 d3 = 07/07/2007 d4 = 01/01/2001 Thursday, May 1, 2003 Thursday, July 5, 2001 Saturday, July 7, 2007 Monday, January 1, 2001 Is Thursday, May 1, 2003 Earlier than Thursday, July 5, 2001? false Here is the code I used to test my program, and what generated the above output: public class DateTest { public static void main(string[] args) { Date d1,d2,d3,d4,d5; d1 = Date.makeDate(1,5,2003); d2 = Date.makeDate(5,7,2001); d3 = Date.makeDate(7,7,2007); d4 = Date.makeDate(1,1,2001); d5 = Date.makeDate(12,45,-6787); if (d5 == null) System.out.println("Invalid Date."); else System.out.println("d5 = " + d5); System.out.println("d1 = " + d1); System.out.println("d2 = " + d2); System.out.println("d3 = " + d3); System.out.println("d4 = " + d4); System.out.println(d1.getFancyDate()); System.out.println(d2.getFancyDate()); System.out.println(d3.getFancyDate()); 8

} } System.out.println(d4.getFancyDate()); System.out.println("Is " + d1.getfancydate() + " Earlier than " + d2.getfancydate() + "? " + d1.isearlier(d2)); 9