AP Computer Science Homework Set 3 Class Methods

Similar documents
AP Computer Science Homework Set 3 Class Methods

AP Computer Science Homework Set 2 Class Design

AP Computer Science Homework Set 2 Class Design

AP Computer Science Homework Set 1 Fundamentals

AP Computer Science Homework Set 1 Fundamentals

AP Computer Science Homework Set 5 2D Arrays

AP Computer Science Homework Set 5 2D Arrays

Homework Set 1- Fundamentals

Homework Set 2- Class Design

CIT Special final examination

Constants are named in ALL_CAPS, using upper case letters and underscores in their names.

9/17/2018 Programming Data Structures. Encapsulation and Inheritance

APCS Semester #1 Final Exam Practice Problems

CS1083 Week 2: Arrays, ArrayList

Chapter 4: Writing Classes

Recommended Group Brainstorm (NO computers during this time)

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

Express Yourself. Writing Your Own Classes

CS 455 Final Exam Fall 2012 [Bono] Dec. 17, 2012

CompuScholar, Inc. 9th - 12th grades

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

CSIS 10B Lab 2 Bags and Stacks

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

public static String[] manyme() {

Assignment 5: Part 1 (COMPLETE) Sprites on a Plane

Collections, Maps and Generics

Ch 7 Designing Java Classes & Class structure

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Chapter 15: Object Oriented Programming

AP CS Unit 7: Interfaces. Programs

Module Contact: Dr Geoff McKeown, CMP Copyright of the University of East Anglia Version 2

Anatomy of a Class Encapsulation Anatomy of a Method

TeenCoder : Java Programming (ISBN )

Back public class HelloWorld { public static void main ( String arg[] ) { Front Basic Setup. Java Quick Sheet. ~ 35 Flashcards. 1 AP CS - Rodriguez

Points off Total off Net Score. CS 314 Final Exam Spring 2016

Csci 102: Sample Exam

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

CS1004: Intro to CS in Java, Spring 2005

AP CS Fall Semester Final

CMPSCI 187 / Spring 2015 Hangman

Set<Integer> s = new TreeSet<Integer>(); s.add( 7 ); s.add( 7 ); System.out.println( s.size() );

Ch 7 Designing Java Classes & Class structure. Methods: constructors, getters, setters, other e.g. getfirstname(), setfirstname(), equals()

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Student Performance Q&A:

Student Performance Q&A:

Week 11: Class Design

Chapter 11: Create Your Own Objects

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Ch 7 Designing Java Classes & Class structure. Fields have data values define/describe an instance

Course materials Reges, Stuart, and Stepp, Martin. Building Java Programs: A Back to Basics Approach. 2d ed. (Boston: Addison-Wesley, 2011).

CMSC 341 Lecture 7 Lists

Programming Assignment Unit 7

Part 1: Group Brainstorm (NO computers during this time) Part 2: Submit Individual Brainstorm (You can now use a computer)

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

AP CSA 3rd Period MR. D. Course Map

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

Initial Coding Guidelines

Ticket Machine Project(s)

Instructions. Objectives:

AP Computer Science Summer Work Mrs. Kaelin

Object Oriented Programming

Chief Reader Report on Student Responses:

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

CS 455 Midterm Exam 1 Fall 2010 [Bono] Sept. 29, 2010

Activity 11: Designing Classes

ECE 122. Engineering Problem Solving with Java

Page 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

IMACS: AP Computer Science A

************ THIS PROGRAM IS NOT ELIGIBLE FOR LATE SUBMISSION. ALL SUBMISSIONS MUST BE RECEIVED BY THE DUE DATE/TIME INDICATED ABOVE HERE

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Practice Midterm Examination

Practice Midterm 1. Problem Points Score TOTAL 50

AP Computer Science in Java Course Syllabus

CS 170 Java Programming 1. Week 12: Creating Your Own Types

CSCI 1226 Second Midterm Test

CompSci 125 Lecture 09. Chapter 5: while, break and continue statements Iterators and the ArrayList Class

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

AP CS Unit 6: Inheritance Programs

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming

Lecture 12: Classes II

EXAM Computer Science 1 Part 1

Object-Oriented Programming Concepts

CSCI 161 Introduction to Computer Science

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics

CMSC 201 Spring 2017 Homework 4 Lists (and Loops and Strings)

Outline for Today CSE 142. Running Example for Today. Song Data Representation. Quick Review Collection classes Iteration and iterators.

Midterm Exam 2 CS 455, Spring 2011

CS Week 14. Jim Williams, PhD

1) Consider the following code segment, applied to list, an ArrayList of Integer values.

Computer Sciences 302 Exam 2 Information & Sample Exam

CS 113 MIDTERM EXAM 2 SPRING 2013

CS 455 Final Exam Fall 2015 [Bono] Dec. 15, 2015

CMSC 202H. Classes and Objects: Reusing Classes with Composition

AP COMPUTER SCIENCE A: SYLLABUS

ASSIGNMENT 4 Classes and Objects

Reviewing all Topics this term

CS108, Stanford Handout #3. HW1 CodeCamp

Transcription:

AP Computer Science Homework Set 3 Class Methods P3A. (BlueJ) Let s upgrade your Song class from P2A. You can make a copy of project P2AProject and rename it P3AProject in your Chapter 3 folder for this program. Here are the specs for the upgrades: a. Add a private instance variable lengthinsecs that stores the duration of the Song in seconds. b. Upgrade the Song s multi-argument constructor to properly initialize the new instance variable lengthinsecs. c. Upgrade the Song s tostring() method to include the length of the Song in the output of the tostring() method. d. Add getter and setter methods for the private instance variable lengthinsecs. These methods will be called getlengthinsec() and setlengthinsec( int newseconds ). In the Java vernacular, getters are also called accessors and setters are also called mutators and allow use to change and view individual instance variables. e. Write a method converttominsec() with the following header: public String converttominsec() It will convert the length of the song into minutes and seconds and output a String representation of it. For example, if the name of the Song is favsong and its length is in seconds is 343, then the following line of code: will print the following: System.out.println( favsong.converttominsec() ) The length of the song is: 5 minutes and 43 seconds. f. Upgrade the Song s tostring() method so that it calls the method converttominsec() as the final line in the tostring() output. g. Write a new SongDriver class to test the following: i. initialize a new Song using the Song s multi-argument constructor. ii. print the result of calling the Song s getter method getlengthinsec() using System.out.println(). iii. change the length of the Song by calling Song s setter method setlengthinsec( int newseconds ), iv. print the result of calling the Song s getter method getlengthinsec() a second time using System.out.println(). v. Call the Song s tostring() method to print all Song info. vi. For practice, write a getminutes() and getseconds() and print the result of each in the driver. Page 1

P3B. (BlueJ)Let s upgrade the Student class from P2B to add the capability to store grades. You can make a copy of project P2BProject and rename it P3BProject for this program. The specifications are listed below: a. Add an instance variable of type array called grades that can hold five double variables for the student s grade point averages for each of his/her classes (English, Math, Science, Fine Arts, Social Sciences). The following scale will be used: A = 4.00 A- = 3.70 B+ = 3.30 B = 3.00 B- = 2.70, etc. b. Upgrade the zero and multi-argument constructors so that it also initializes the array of grades with 5 double values in the following order: English Math Science Fine Arts Social Science d. Add a public method, calcgpa(), that will calculate and return the average GPA for the student as a double value. This method should use a for loop to traverse the array grades, calculate the sum of the grades in the array and divide by the total number of grades to arrive at the GPA. Note that this method should work if the size of the array is changed (i.e., classes are added or dropped). Don t assume that the length of the array is 5. e. Add a public getter and setter methods to set and get the Math GPA only. Typically, we would add getters and setters for each instance variable, but we ll just practice with one for now. f. Upgrade the tostring() method that will return a String that includes the student s name, and average GPA. Sample out is shown below: Student: Mickey Mouse Cumulative GPA: 3.97 Page 2

Write a driver class to: i. Create a Student senior using the multi-argument constructor with following midterm grade information: First Name = Joe Last Name = Senior English = 3.0 Math = 3.0 Science = 3.5 Fine Arts = 4.0 Social Science = 4.0 ii. iii. iv. printout the student s name and average GPA using the tostring() method, set the student s math grade to a 4.0 using the setmath() setter method. print the student s math grade using the getmath() getter method. v. print the result of the brain method calcgpa(). vi. printout the student s name and average GPA using the tostring() method a second time after the grade change. Page 3

P3C. (Greenfoot) Spaceship Flight Statistics In this program, you ll upgrade your Spaceship from P2C to include two new brain methods that will perform flight calculations. a. Include instance variables for the x and y coordinates for the interstellar travel destination, xdestination and ydestination, respectively. a. Trip Distance - Write a brain method calctripdistance() that will calculate the distance between your current location in space and a destination location in space. Method calctripdistance() should have the following header: public double calctripdistance() Method calctripdistance() will calculate and return the distance between the Spaceship s current position and the x and y coordinates of the destination as shown below: ( ) 2 + ( x dest getx() ) 2 d = y dest gety () (where all distances are in km) b. Trip Time Write the brain method calctriptraveltime() that will calculate the time needed to travel the distance based on the speed of your Spaceship. Method calctriptraveltime() should have the following header: public double calctriptraveltime() You can use the average speed equation to calculate the time as shown below: speed = d t where speed is in km/hr, d = distance in km, and t = time in hours. The distance d in the above equation should be the distance returned by the calctripdistance() method. c. Print the result of the calctripdistance() and calctriptraveltime() methods in Spaceship s act() method using the following line of code: getworld().showtext( "Distance to destination is: " + calctripdistance() + " km", getworld().getwidth()/2, getworld().getheight() - 100 ); Use a similar line of code to print calctriptraveltime(). Page 4

Example 1 (assuming Spaceship has speed of 50 [km/hr] Example 2 (assuming Spaceship has speed of 50 [km/hr] Page 5

Sample Output for P3C Page 6

P3D. (Greenfoot) Spaceship Flight Training As part of your training, you will demonstrate your piloting skills. The requirements for this training exercise are listed below. You can make a copy of project P2CProject and rename it P3DProject for this assignment. Mission Requirements: a. Starting at the interstellar coordinate (0,0), your Spaceship will traverse the known universe from left to right (one pixel at a time) until you reach the right-most boundary of space, print the x and y coordinates of your Spaceship each time the Spaceship s act() method is called. Add a boolean instance variable ismissionaccomplished (initially set to false), that you will set to true when your mission is accomplished. The following two methods can be called from your Spaceship object to determine the dimensions of your Universe (aka World): getworld().getwidth(); getworld().getheight(); If you set the dimensions of your Universe to 800, 600 using: super(800, 600, 1); Then, getworld().getwidth(); would return 800, and getworld().getheight(); would return 600 b. After the right boundary of space is reached, turn right, move down 1 pixel, turn right again and continue to traverse space right-to-left until the left-most boundary of the Universe is reached. When you reach the leftmost boundary of space, turn left, move down 1 pixel, and turn left again. Continue this pattern until you have reached the last possible corner of the Universe. c. Once you have reached the last possible corner of the Universe, complete the following: i. Teleport to the exact center of the Universe by using Spaceship s method setlocation( int newx, int newy ). Recall that you can calculate the center of the universe by using the getworld().getwidth() and getworld().getheight() methods shown above. ii. Set the value of ismissionaccomplished to true. iii. iv. Display the message Mission Complete! using getworld().showtext(). Use the Greenfoot.stop() method to end the program. If you don t use this method, Greenfoot will continue to run your Spaceship s act() method indefinitely. Page 7

P3E. (BlueJ) APLine (AP Exam Question 2010 #2) Write the APLine class as described on the handout. You will be sent a BlueJ project that includes an APLineDriver and an empty APLine class that you will use to complete this program. The following programs DO NOT need a separate class and driver files. They are stand-alone programs that are meant to review previous topics (and introduce a couple of new concepts) P3F. (BlueJ) Write a program that creates three String objects. Each String should be the name of a university to which you are applying. We will now compare the universities with the String method compareto(). Print out the result of comparing each school to another. For example, if s1 and s2 are defined as follows: String school1 = new String ( UCLA ); String school2 = new String ( UCSD ); String school3 = new String ( Stanford ); We can compare the schools as follows: System.out.println( school1.compareto( school2 ); Answer the questions below in a comment after all of your source code: a. What is the output of the compareto() method represent? b. In the example above, UCLA and UCSD have the same number of letters AND the first two letters are identical. What does the compareto() method return in this case? Page 8

P3G. (BlueJ) Write a program that searches for a given integer in an array of integers. Specifically, write a program to perform the following tasks: a. create and print an array consisting of the 10 integers shown below. Initialize these as shown; don t use Math.random(). -9 2 3 4 7 9 10 23 45 67 b. use a for loop to traverse the array and return the index number of the location of the integer you wish to find. For example, in the array above, if the number to find is 9, the program should return the index number 5 in a user-friendly phrase. c. If the number is NOT found in the array, return -1. P3H. (BlueJ) Write a program that will sum the digits of a given integer. Specifically, the program will perform the following tasks: a. Create a class called MyInteger that consists of the Big 3 : i. a single integer instance variable called num, ii a one-argument constructor that will initialize the value of num, iii. a tostring() method that will print the value of the instance variable num in a user-friendly format. b. Calculate the sum of the digits of the instance variable num in the brain method calculatesum(). The method calculatesum() shall have the following header: public int calculatesum() For instance, if the value of num is initialized to the value of 123456, the result of calculatesum should be: 1 + 2 + 3 + 4 + 5 + 6 = 21. c. Write the driver class MyIntegerDriver that will perform the following tasks: i. create an instance of the MyInteger class using its one-argument constructor, ii. print the value of the instance variable num using the class tostring() method, and iii. call and print the result of the method calculatesum(). Page 9

P3I. (BlueJ) We are now going to learn about another type of array called ArrayList that can hold objects. One way ArrayLists are different from arrays is that you don t have to specify the number of elements in the ArrayList when you create it (as you do with regular arrays). This flexibility allows you to add and delete objects from the ArrayList as you wish and the ArrayList will take care of the resizing and re-indexing of elements itself. a. Write a program that creates an ArrayList that can hold String objects. Populate the ArrayList with the names of the schools to which you are applying. See LewTube videos for demos on how to create and use ArrayLists and all of its methods. The code below shows how to create an ArrayList of Strings: // include these as the first lines of your program // to allow you to use the ArrayList object import java.util.list; import java.util.arraylist; List<String> colleges = new ArrayList<String>() You can use the ArrayList s add() method to add object to the ArrayList as shown below (include at least 5 schools in your ArrayList): colleges.add( UCLA ); colleges.add( Penn ); b. Use a for loop to traverse the ArrayList and print the names of each of the schools you are applying to. We can use ArrayList s.size() method to determine the number of element in the ArrayList. Include an if statement to test possible null entries. c. Now use a for-each loop to traverse the ArrayList and print the names of each of the schools. See the LewTube video on how to use the for-each loop to traverse ArrayLists. d. Now let s remove one of the schools that you are no longer applying to using the.remove() method. You can remove an element using the following syntax: colleges.remove( 1 ); // this will remove element 1 and resize the ArrayList e The add() method that we used in part (a) added elements to the end of the ArrayList. There is another version of the add method that allows you to add an element anywhere in the list. You can add an element anywhere in the list using the following syntax: colleges.add( 1, Santa Clara ); // this will add element Santa Clara at element number 1 and // resize the ArrayList Page 10

P3J. (BlueJ) Write a Create new password program that requires passwords to have a length of at least 6 characters and at least one non-alphanumeric character (+, -, *, /, or @.) Passwords that do not meet these requirements should be rejected. Use the String method substring() which returns String that is part of or substring of a given String. Consider the following example: String password = new String( "abc*d_" ); System.out.println( password.substring( 3,4 ) ); // prints * What do you think the arguments 3 and 4 represent? Since the substring method returns a String, you can compare it to another String using.equals(). The example below shows how we can extract one letter from the password and determine if it is equal to *. String oneletter = new String( password.substring( 3,4 ) ); oneletter.equals( * ); // result is true If a successful password has been entered, the program should end (i.e., the program should not ask the user for another password or remain in an endless loop). Page 11

Learning Objective Checklist (please print and complete after you have had all HW Set 3 programs checked off) Place a check next to those items that you have mastered Write getter and setter methods for instance variables in a class. Write brain methods for a class that perform algorithmic processing for a class. Use the substring() method of the String class to extract a letter or letters from a String. Use the +=, -=, *=, /=, and %= operators to accumulate values in calculations. Create an instance of class ArrayList of any given object type. Populate an ArrayList with objects using the ArrayList s add() method. Get number of elements in an ArrayList using the ArrayList s size() method. Traverse an ArrayList using a for loop. Traverse an ArrayList using a for-each loop. Traverse an array using a for loop. Traverse an array using a for-each loop. Page 12