Introduction to Computer Science Unit 4B. Programs: Classes and Objects

Similar documents
Introduction to Java Programs for Packet #4: Classes and Objects

Introduction to Computer Science Unit 3. Programs

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

AP CS Unit 4: Classes and Objects Programs

1 Short Answer (10 Points Each)

Introduction to Computer Science Unit 5. Programs: Strings

AP Computer Science Unit 1. Programs

COMP 110 Programming Exercise: Simulation of the Game of Craps

Lab 9: Creating a Reusable Class

Introduction to the Java Basics: Control Flow Statements

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

1 Short Answer (2 Points Each)

AP Computer Science Unit 3. Programs

Warm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2

CS Week 13. Jim Williams, PhD

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

Introduction to Computer Science Unit 2. Notes

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

2.2 - Making Decisions

AP Computer Science Unit 1. Writing Programs Using BlueJ

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012

PROGRAMMING FUNDAMENTALS

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Introduction to Computer Science Unit 2. Exercises

static String usersname; public static int numberofplayers; private static double velocity, time;

Introduction to Computer Programming

BLOCK STRUCTURE. class block main method block do-while statement block if statement block. if statement block. Block Structure Page 1

1 Short Answer (5 Points Each)

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

Introduction to Computer Science Unit 2. Notes

Midterm Examination (MTA)

Introduction to Java Unit 1. Using BlueJ to Write Programs

University of Massachusetts Amherst, Electrical and Computer Engineering

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Lesson 26: Volume of Composite Three-Dimensional Objects

Practice Midterm 1. Problem Points Score TOTAL 50

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

for Middle School

AP Computer Science Unit 1. Writing Programs Using BlueJ

CONDITIONAL EXECUTION

CS 120 Fall 2008 Practice Final Exam v1.0m. Name: Model Solution. True/False Section, 20 points: 10 true/false, 2 points each

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

2 + (-2) = 0. Hinojosa 7 th. Math Vocabulary Words. Unit 1. Word Definition Picture. The opposite of a number. Additive Inverse

CIS 120 Midterm II March 31, 2017 SOLUTIONS

Chapter Goals. Contents LOOPS

1 Short Answer (15 Points Each)

Question 1 [20 points]

Geometry Workbook WALCH PUBLISHING

COMP 202 Java in one week

CS1150 Principles of Computer Science Loops (Part II)

Building Java Programs

Surface Area and Volume

2009 Fall Startup Event Thursday, September 24th, 2009

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function

AP CS Unit 3: Control Structures Notes

Quiz 1 Unit 5A Arrays/Static Name

CSIS 10A Assignment 9 Solutions

Problem Grade Total

Introduction to Computer Science Exercises for Unit 4A: Classes and Objects 1. This compiles and runs. What is displayed?

AP CS Unit 6: Inheritance Programs

M e t h o d s a n d P a r a m e t e r s

Assignment 2.4: Loops

CS 112 Introduction to Programming

CS 112 Introduction to Programming

assertion: A statement that is either true or false.

APCS Semester #1 Final Exam Practice Problems

Building Java Programs

Java Outline (Upto Exam 2)

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

Building Java Programs

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Static Methods. Why use methods?

int a; int b = 3; for (a = 0; a < 8 b < 20; a++) {a = a + b; b = b + a;}

Java GUI Test #1 Solutions 7/10/2015

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

This exam is open book. Each question is worth 3 points.

1 Short Answer (10 Points Each)

Recommended Group Brainstorm (NO computers during this time)

Repetition, Looping. While Loop

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Building Java Programs

CC112 Structured Programming

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

5. What is a block statement? A block statement is a segment of code between {}.

Introduction to Classes and Objects. David Greenstein Monta Vista High School

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Give one example where you might wish to use a three dimensional array

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

Lesson 26: Volume of Composite Three-Dimensional Objects

Name ANSWER KEY Date Period Score. Place your answers in the answer column. Show work clearly and neatly. FOCUS ON WHAT IS NECESSARY FOR SUCCESS!

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Transcription:

Introduction to Computer Science Unit 4B. Programs: Classes and Objects This section must be updated to work with repl.it 1. Copy the Box class and compile it. But you won t be able to run it because it does not have a main method. Create a second class file named TestBoxes which has a main method. In the main method do the following: - create a Box object 2 ft wide by 6 ft long - call the getarea method and display the result - call the bigger method and double the dimensions of the box - call the getperimeter method and display the result public class Box { private double length, width; public Box( double len, double wid ) { length = len; width = wid; public double getarea() { return length * width; public double getperimeter () { double p = 2.0*( length + width); return p; 2. Copy the DiceRunner class and complete the Dice class. Compile and run. Set a breakpoint to check if the doubles method works correctly. public class DiceRunner { public static void main(string[] args) { Dice d = new Dice(); d.roll(); int n = d.gettotal(); System.out.println( n ); if ( d.doubles() ) System.out.println( "Yes" ); d.roll(); n = d.gettotal(); System.out.println( n ); public void bigger( double f ){ length = f * length; width = f * width; public class Dice { private int die1, die2; public Dice() { die1 = 0; die2 = 0; public void roll() { Assign die1 a random integer value between 1 and 6. Do the same thing for die2. Use Math.random(). public int gettotal() { return the sum of die1 and die2

if ( d.doubles() ) System.out.println( "Yes" ); public boolean doubles() { return true if both die are the same; otherwise return false. 3. Write another class (with a main method) in the same location as the files you created for Problem 2. In this main method, create one Dice object and roll the dice 100 times (in other words, call the roll method followed by the gettotal method 100 times). Count how many times you roll a 7 or 11. Also count how many times you rolled a 2, 3, or 12. And count how many doubles you got. Display the results as percents. For example: You rolled a 7 or 11 21% of the time. You rolled a 2, 3, or 12 13% of the time. You rolled doubles 15% of the time Note. Take advantage of the fact that you are rolling the dice 100 times to calculate the percentages 4. Copy the Circle class and complete the two methods to the right. getc should return the circumference of the circle and changer should assign the value of the parameter to the radius. Write a second class with a main method. In the main method: - create a Circle object with a radius of 3. - call the getc method and display the returned value (it should be 18.84955592153876 ) - call the getarea method and display the returned value (it should be 28.274333882308138) - call the changer method and change the circle s radius to 1. - call the getarea method again and display the returned value (it should 5. Write the Employee class so that when the main method in RunEmployee is executed, the following is displayed. Salary is 42000.0 Salary is 41500.0 Salary is 44500.0 public class Circle { private double radius; public Circle( double r ) { radius = r; public double getarea() { double a = Math.PI * radius * radius; return a; public double getc () { it returns the circle s circumference public void changer( double r ) { changes the value of radius to r public class RunEmployee { public static void main(string[] args) { Employee e = new Employee(40000.0); e.increase( 2000.0 ); double p = e.getpay(); System.out.println( "Salary is " + p ); e.increase( -500.0 );

The Employee class has one instance variable for storing an Employee s salary. p = e.getpay(); System.out.println( "Salary is " + p ); Note: the increase method should change the value of the instance variable. The getpay method simply returns the value of the instance variable. e.increase( 3000.0 ); p = e.getpay(); System.out.println( "Salary is " + p ); 6. Finish the Travel class. Then write a second class that has a main method. In the main method: - Write a loop that iterates 21 times with the counter going from 6 to 40 in steps of two. - In the body of the loop, create a Travel object and call each method. Print the returned values. - The output should look like this: people = 6, vans = 1, canoes = 2, planes = 1 people = 8, vans = 1, canoes = 3, planes = 1 people = 10, vans = 2, canoes = 4, planes = 1 people = 12, vans = 2, canoes = 4, planes = 1 people = 14, vans = 2, canoes = 5, planes = 2... people = 32, vans = 4, canoes = 11, planes = 3 people = 34, vans = 5, canoes = 12, planes = 3 people = 36, vans = 5, canoes = 12, planes = 3 people = 38, vans = 5, canoes = 13, planes = 4 people = 40, vans = 5, canoes = 14, planes = 4 7. The Prism class represents a rectangular prism. Complete the two methods. 8. Write another class that has a main method. In the main method: -Create a Scanner object and have the user enter three integers. - Instantiate a Prism object using those three integers. - Call the surfacearea method and print the returned value. - Call the issmall method. If it returns true, print This is a small prism. If the method returns false, print This is not a small prism. Here is sample output. public class Travel { private int people; public Travel( int n ) { people = n; public int gobyvan(){ this returns the number of vans required to transport everyone (8 per van) public int gobycanoe(){ this returns the number of canoes required (3 per canoe) public int gobyplane() { this returns the number of planes required (12 per plane) public class Prism{ private int len, w, h; public Prism( int a, int b, int c ) { len = a; w = b; h = c; public int surfacearea(){ Calculates and returns the surface area of the prism. public boolean issmall(){

Enter the length, width, height 4 3 5 Its surface area is 94 square units This is a small prism 9. Copy the Car class. In another class s main method, create two car objects. Write a while loop where the drive method is called for each car and their locations are printed. When a car has gone over 200 miles, the loop stops and that car is the winner. Here is one sample output. Car 1: 4 miles, Car 2: 36 miles. Car 1: 14 miles, Car 2: 71 miles. Car 1: 17 miles, Car 2: 75 miles. Car 1: 156 miles, Car 2: 178 miles. Car 1: 167 miles, Car 2: 217 miles. Car 2 wins But obviously sometimes Car 1 will win and there could even be a tie. 10. First complete the Number class. Then we play the guessing game. Each turn the user gets to ask if the secret number is a multiple of some number and then they get to guess the secret number. Here's a rough outline. public class Runner { public static void main(string[] args) { create a Scanner object create a Number object boolean keepplaying = true; int count = 0; while ( keepplaying ) { count++; Ask the user to enter a positive integer. Get response and call the multipleof method. Print a message that indicates if the secret number is a multiple of that input or not Ask the user to guess what the secret number is. Call the guess method. If the user s right then print Congratulations, print count, and set keepplaying to false (to get out of the loop). If the user is wrong, then indicate that. Calculates the volume of the prism. If the volume is less than 75 cubic units, then this is a small prism and the method returns true. Otherwise the method returns false. public class Car { private int x; // location of the car public Car( ) { x = 0; public int getx(){ return x; public void drive() { x= x + (int)( 40*Math.random()); public class Number { private int num; public Number( ) { num = (int)(100*math.random() )+1; public boolean multipleof( int x ){ returns true if num is a multiple of x public boolean guess( int x ) { returns true if num equals x; otherwise it returns false Enter an integer: 2 The number is NOT a multiple of 2 Guess the secret number: 13 That s not it. Enter an integer: 3 The number is a multiple of 3

Guess the secret number: 3 That s not it. To the right is one possible outcome (though it will probably take more than 3 tries to guess the number). Enter an integer:5 The number is a multiple of 5 Guess the secret number: 45 You to it in 3 tries. 11. The Line class objects represent simple linear equations that can be written in slope-intercept form. Complete the two methods of the Line class. 12. Write another class that has a main method. In the main method, create a Scanner object and write a loop that repeats five times. In the loop: Create a random slope (using Math.random) that is one of the following values: -3.0, -2.5, -2.0,... 2.5, 3.0 If you get stuck on this, the code is below*. Create a random y-intercept that is an integer between -3 and +3. Create a Line object using the random slope and y-intercept. Call the display method. Generate a random x value between 0 and 10. Call the gety method and use this random value. Display the x and y values. Have the user enter x and y values. Call the issolution method to check if those values are a solution to the linear equation or not. Display an appropriate message. Print a blank line. * Here is one way to generate the random decimal values for the slope. int num = (int) (13*Math.random() ) - 6; double slope = 0.5 * num; public class Line{ public double slope, intercept; public Line( double m, double b ){ slope = m; intercept = b; public void display(){ if ( slope == 0 ) SOP( "y = " + intercept ); else if ( intercept < 0 ) SOP("y = " + slope +"x " +intercept); else if ( intercept == 0 ) SOP( "y = " + slope + "x" ); else SOP("y = " + slope + "x +" + intercept); public double gety( double x ){ Given a value for x, return the corresponding value for y public boolean issolution(double x, double y ){ Returns true if the parameters are a solution of the Line. Otherwise it returns false. Your solution may sometimes return false when it should return true due to small errors that can arise working with doubles. Ignore this problem or ask me how to solve it. Here s some sample output for this problem. y = -2.0x + 1.0 If x is 8.0, then y is -15.0 Check if a point is a solution. Enter x then y -1.5 4 (-1.5, 4.0 ) is a solution to this equation

y = 1.0x -2.0 If x is 1.0, then y is -1.0 Check if a point is a solution. Enter x then y 0 2.5 (0.0, 2.5) is NOT a solution to this equation y = -1.0x -2.0 If x is 7.0, then y is -9.0 Check if a point is a solution. Enter x then y 7-9.0 (7.0, -9.0) is a solution to this equation 13. Complete the move method of the GamePiece class. 14. Write another class that has a main method. In the main method, create two GamePiece objects. Keep calling the move method for each object until one of the two objects gets to 21. The output should look something like this: Player 1 has 4, Player 2 has 2 Player 1 has 8, Player 2 has 6 Player 1 has 9, Player 2 has 11 Player 1 has 16, Player 2 has 17 Player 1 has 17, Player 2 has 20 Player 1 has 18, Player 2 has 5 Player 1 has 3, Player 2 has 9 Player 1 has 8, Player 2 has 10 Player 1 has 12, Player 2 has 16 Player 1 has 14, Player 2 has 19 Player 1 has 16, Player 2 has 1 Player 1 has 21, Player 2 has 3 Player 1 wins public class GamePiece{ private int number; public GamePiece(){ number = 0; public void move(){ If number is 21, then do nothing. Otherwise, generate a random integer between 1 and 7 and add this to the instance variable. However, the instance variable should never have a value greater than 21. If it is 22, then reduce it to 1. If it is 23, then it becomes 2, and so on. public int getnumber(){ return number;