Assignment 1-Sample Solutions PDF

Title Assignment 1-Sample Solutions
Author Abdulrehman Arif
Course Introduction to Java
Institution University of Windsor
Pages 13
File Size 398.9 KB
File Type PDF
Total Downloads 46
Total Views 170

Summary

Download Assignment 1-Sample Solutions PDF


Description

Computer Science COMP-2120 - Winter 2020 Assignment 1 !Due: End of Friday, February 7, 2020 ************************** Note: Submit your assignment as a single zip file on Blackboard. The zip file should be named as Assignment1_StudentId.zip, in which replace StudentId with your university student number. The zip file should include only one text file and several Java files, i.e. files with the extension name “.java”. DO NOT include any compiled class file. For every problem, follow the name of the files as instructed. For problem 2, put your answers in a text (txt) file. ************************** Problem 1. (4 points) Goal: Practice arithmetic operations in Java. Write a Java program, in which declare and initialize required variables with some arbitrary values, and compute the following mathematical operations: (

01

,

𝐺 = 𝜋) # .

𝑠 = # 𝑠$ ∗ # 𝑣$ − # 𝑔 ∗ # 𝑡 , )

3 24 (63 764 )

Java file name: Problem1.java public class Problem1{ public static void main(String[]args) { double s; double s0 = 10; double v0 = 100; double g = 9.8; double t = 5; s = s0 * v0 - (1/2.0) * g * Math.pow(t,3); double a = 5; double p = 2; double m1 = 3; double m2 = 7; double G = (3 / 4.0) * Math.pow(Math.PI,2) * ( Math.pow(a,3) / (Math.sqrt(p) * (m1 - m2))); } }

Problem 2. (8 points) Goal: Practice arithmetic operation and the meaning and order of the mathematical operations in Java. What are the values of the following expressions? In each line assume that double x = -3.5; double y = 1.9; int n = 23; int m = 14; a.

!

x - n / y + x + (n * y) = -3.5 - 23 / 1.9 – 3.5 + (23 * 1.9) = 24.5947...

1!

b. c. d. e. f. g. h.

n / m + n % m = 23 / 14 + 23 mod 14 = 10 n % 2 + m % 3 = 23 mod 2 + 14 mod 3 = 3 (m + n) / 3.0 = (14 + 23) / 3.0 = 12.333... (n - m) / 3 = (23 - 14) / 3 = 3 (n – x) / 3 = (23 + 3.5) / 3 = 8.8333... 1 - (1 - (1 - 23)) = 1 – (1 – (1 – 23) = -22 m % 10 + (m – (n % 10)) = 14 mod 10 + (14 – (23 mod 10)) = 15

File name: Problem2.txt Problem 3. (9 points) Goal: Practice how to use Java API by creating objects from standard Java classes in our Java code. Browse the Java API Documentation on Internet and try to find two classes, one for creating twodimensional lines, and one for creating two-dimensional ellipses. Then, write a Java program, to do the following tasks: 1- Create a line with the following initial values: from the point (3, 12) to the point (17, 31) 2- Change the end point of the line to (19, 13). 3- Create an ellipse with the following initial values: Height=25, Width=60, The x coordinate of the upper-left corner of the framing rectangle of this ellipse = 4 The y coordinate of the upper-left corner of the framing rectangle of this ellipse = 13 After each of the following steps, test your program by printing the actual and expected results. Note*: In this example, we just want to create objects and not drawing them on the screen. Java file name: Problem3.java import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; public class Problem3 { public static void main(String[] args){ Line2D.Double line = new Line2D.Double(3, 12, 17, 31); System.out.println("Line from: ("+line.x1+","+line.y1+") to: ("+line.x2+","+line.y2+")"); System.out.println("Expected Line from: (3,12) to: (17,31)"); line.setLine(3,12,19,13); System.out.println("Line from: ("+line.x1+","+line.y1+") to: ("+line.x2+","+line.y2+")"); System.out.println("Expected Line from: (3,12) to: (19,13)");

!

2!

Ellipse2D.Double ellipse = new Ellipse2D.Double(4, 13, 25, 60); System.out.println("Ellipse from: ("+ellipse.x+","+ellipse.y+") dimension: ("+ellipse.width+","+ellipse.height+")"); System.out.println("Expected Ellipse from: (4,13) dimension: (25,60)"); } }

Problem 4. (10 points) Goal: Practice how to create user-defined classes in Java. A microwave control panel has five buttons: 1) one for increasing the time by 30 seconds, 2) one for switching between power levels, Low, Medium, and High, 3) a stop button, 4) a reset button, and 5) a start button. Implement a class that simulates the microwave, with a method for each button. The method for start button should print a message “Cooking for … seconds at level …” and changes the current status of the microwave. The method for stop button should print a message “Cooking stopped.” and changes the current status of the microwave. Based on the above description, you must figure out the required properties of the microwave control panel. At the end, write a separate Java program as the tester to test your microwave class with different values. Note*: There is no graphical task in this problem. Java file names: Microwave.java and TestMicrowave.java /** A class for representing a microwave oven. */ public class Microwave { private int time; private int powerLevel; private int status; public static final int STOPPED = 0; public static final int RUNNING = 1; /** Creates a microwave with 0 seconds on the timer and at low power. */ public Microwave(){ time = 0; powerLevel = 0; } /** Increases the time on the timer by 30 seconds. */ public void increaseTime(){ time = time + 30; } /** Switches the power level from low to high, or vice versa. */ public void switchPower(){ powerLevel = (powerLevel + 1) % 3; } /** Resets the microwave to its initial state. */ public void reset(){ time = 0; powerLevel = 0; }

!

3!

/** Starts the machine, displaying information about its cooking state. */ public void start(){ System.out.print("Cooking for " + time + " seconds "); System.out.println("at level " + (powerLevel + 1)); this.status = RUNNING; } /** Stops the machine, displaying information about its cooking state. */ public void stop(){ System.out.println("Cooking stopped."); this.status = STOPPED; } } public class MicrowaveTester { public static void main(String[] args) { Microwave appliance = new Microwave(); appliance.increaseTime(); appliance.increaseTime(); appliance.increaseTime(); appliance.switchPower(); appliance.start(); System.out.println("Expected: Cooking for 90 seconds at level medium"); appliance.reset(); appliance.increaseTime(); appliance.switchPower(); appliance.switchPower(); appliance.start(); System.out.println("Expected: Cooking for 30 seconds at level high"); appliance.stop(); System.out.println("Expected: Cooking Stopped."); } }

Problem 5. (9 points) Goal: Practice how to create user-defined classes in Java. Enhance the BankAccount class and see how abstraction and encapsulation enable evolutionary changes to software: • Begin with a simple enhancement: charging a fee for every deposit and withdrawal. Supply a mechanism for setting the fee and modify the deposit and withdraw methods so that the fee is levied. The initial transaction fee is 50 cents, and this can be changed later on. Test your class and check that the fee is computed correctly. • Now make a more complex change. The bank will allow a fixed number of free transactions (deposits and withdrawals) every month, and charge for transactions exceeding the free allotment. The charge is not levied immediately but at the end of the month. The initial value for the number of free transactions is 10. Supply a new method deductMonthlyCharge to the BankAccount class that deducts the monthly !

4!



charge and resets the transaction count. (Hint: Use Math.max(actual transaction count , free transaction count) in your computation.) Write a tester Java program that verifies that the fees are calculated correctly over several months.

Java file names: BankAccount.java and TestBankAccount.java /** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { private double balance; private int transactions; private int freeTransactions; private double transactionFee; public BankAccount(){ balance = 0; transactionFee = 0.50; transactions = 0; freeTransactions = 10; } /** Constructs a bank account with a given balance. @param initialBalance the initial balance @param free number of free transactions */ public BankAccount(double initialBalance, int free){ balance = initialBalance; transactionFee = 0.50; transactions = 0; freeTransactions = free; } /** Deposits money into the bank account. @param amount the amount to deposit */ public void deposit(double amount){ balance = balance + amount; transactions = transactions + 1; } /** Withdraws money from the bank account. @param amount the amount to withdraw */ public void withdraw(double amount){ balance = balance - amount; transactions = transactions + 1; } /** Gets the current balance of the bank account. @return the current balance */ public double getBalance(){

!

5!

return balance; } /** Sets the transaction fee. @param fee new transaction fee */ public void setTransactionFee(double fee){ transactionFee = fee; } /** Applies monthly transaction charge. */ public void deductMonthlyCharge(){ int chargedTransactions = Math.max(transactions, freeTransactions) - freeTransactions; balance = balance - transactionFee * chargedTransactions; transactions = 0; } } public class BankAccountTester { public static void main(String[] args) { BankAccount acc1 = new BankAccount(); BankAccount acc2 = new BankAccount(800,2); System.out.println("Expected: acc1 balance: System.out.println("Actual: acc1 balance: " System.out.println("Expected: acc2 balance: System.out.println("Actual: acc2 balance: "

0.0"); + acc1.getBalance()); 800.0"); + acc2.getBalance());

acc1.deposit(1000); System.out.println("Expected: acc1 balance: 1000.0"); System.out.println("Actual: acc1 balance: " + acc1.getBalance()); acc1.withdraw(200); acc1.withdraw(200); acc1.withdraw(200); System.out.println("Expected: acc1 balance: 400.0"); System.out.println("Actual: acc1 balance: " + acc1.getBalance()); acc2.withdraw(100); acc2.withdraw(200); acc2.withdraw(50); System.out.println("Expected: acc2 balance: 450.0"); System.out.println("Actual: acc2 balance: " + acc2.getBalance()); acc1.deductMonthlyCharge(); System.out.println("Expected: acc1 balance: 400.0"); System.out.println("Actual: acc1 balance: " + acc1.getBalance()); acc2.deductMonthlyCharge(); System.out.println("Expected: acc2 balance: 449.5"); System.out.println("Actual: acc2 balance: " + acc2.getBalance()); } }

Problem 6.

!

(25 points)

6!

Goal: Practice how to create user-defined classes in Java. Design a Java class for Person with the following behaviours: • talk, in which a person can talk a sentence, if s/he is at least two-year old. • eat, in which a person can eat something if s/he is hungry. If the person eats something, then s/he becomes full (not hungry). • needFood, in which the person’s status will become hungry if s/he is currently full. • walk, in which a person will walk a specific distance. If a person walks more than four kilometers, then s/he becomes tired and is not able to walk anymore. • sleep, in which a person will sleep if s/he is awake. If a person sleeps, then s/he is no tired anymore, her/him walking distance will reset, and s/he can walk again. Note that if a person is sleeping, s/he can’t walk. • awake, in which the person is awaken if s/he is currently sleeping. • grow, in which the person’s age will increase by one year. If a person reaches to 55, then his ability to walk will decrease by half every five years. You need to indicate all the instance variables (properties) a give person should have to be able to handle the above list of behaviors and store the current states of a given person. For instance, every person has name, age, current distance of walking, sleeping status, walking distance capability, etc. After designing the Person class, implement it as a Java class. Then write a tester Java program to test that class by creating some Person instance objects and do some actions for each of them. To make sure that your tester program tests all the functionalities of a given person, you have to call every method of the class at least once. Assume that every person can have one friend, which is another person. Therefore, two other behaviors for a person could be getFriend and changeFriend. Modify the Person class that you have designed to be able to handle these two behaviours as well. Note that you need to have another instance variable as well. Java file names: Person.java and TestPerson.java public class Person { private String name; private int age; public enum HStatus {HUNGRY, FULL}; private HStatus hungerStatus = HStatus.HUNGRY; private float distanceWalked; public static final int MAXIMUM_WALK = 4000; private float walkingCapability = MAXIMUM_WALK; public enum SStatus {SLEEP, AWAKE}; private SStatus SleepStatus = SStatus.AWAKE; private Person friend; public Person() { this.name = ""; } public Person(String name) { this.name = name; } public Person(String name, int age) {

!

7!

this.name = name; this.age = age; } public void talk(String s) { if (this.age >= 2) System.out.println(this.name + " says: " + s); else System.out.println(this.name + " is too young to be able to talk."); } public void eat(String food) { if (this.hungerStatus == HStatus.HUNGRY) { System.out.println(this.name + " eats: " + food); this.hungerStatus = HStatus.FULL; } else System.out.println(this.name + " is full and can't eat."); } public void needFood() { if (this.hungerStatus == HStatus.FULL) { this.hungerStatus = HStatus.HUNGRY; System.out.println(this.name + " is now hungry."); } } public void walk(float distance) { if (this.SleepStatus == SStatus.AWAKE) { if (this.distanceWalked >= MAXIMUM_WALK) System.out.println(this.name + " has walked 4 or more KMs and is tired."); else { this.distanceWalked += distance; System.out.println(this.name + " just walked " + distance + " meters. (" + this.distanceWalked + " meters walked so far.)"); } } else System.out.println(this.name + " is sleeping and therefore can't walk now."); } public void sleep() { if (this.SleepStatus == SStatus.AWAKE) { setSleepStatus(SStatus.SLEEP); this.distanceWalked = 0; System.out.println(this.name + " just slept and won't be tired anymore."); } else { System.out.println(this.name + " is not awake and is still sleeping."); } } public void awake() { setSleepStatus(SStatus.AWAKE); } public void grow() { this.age++; if (this.age > 60) { float f = MAXIMUM_WALK / (2 * (1 + ((age - 60) / 5))); if (Math.abs(f - this.walkingCapability) > 0) { this.walkingCapability = f;

!

8!

System.out.println(this.name + " is getting old (" + this.age + ") and is now capable to walk " + this.walkingCapability + " meters, maximum."); } } } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } public float getDistanceWalked() { return distanceWalked; } public float getWalkingCapability() { return walkingCapability; } public void setSleepStatus(SStatus sleepStatus) { this.SleepStatus = sleepStatus; } public Person getFriend() { return this.friend; } public void changeFriend(Person friend) { this.setFriend(friend); } public void setFriend(Person friend) { this.friend = friend; friend.friend = this.friend; } } public class PersonTester { public static Person p1 Person p2 Person p3

void main(String[] args) { = new Person("John"); = new Person("Alice", 19); = new Person();

p1.setAge(1); p3.setName("Rose"); p3.setAge(57); System.out.println(p1.getName() + ", " + p1.getAge() + " years old."); System.out.println(p2.getName() + ", " + p2.getAge() + " years old."); System.out.println(p3.getName() + ", " + p3.getAge() + " years old.");

!

9!

Person p2Friend = p2.getFriend(); if (p2Friend == null) System.out.println(p2.getName() + " has no friend."); else System.out.println(p2.getName() + "'s friend is " + p2Friend.getName() + "."); p2.walk(1500); p2.changeFriend(p3); System.out.println(p2.getName() + " is friend with " + p2.getFriend().getName() + "."); System.out.println(p3.getName() + " is friend with " + p3.getFriend().getName() + "."); p2.walk(1000); p2.walk(1500); p2.walk(1000); p2.sleep(); p2.walk(1000); p2.awake(); p2.walk(1000); p3.grow(); System.out.println(p3.getName() + ", " + p3.getAge() + " years old."); System.out.println(p3.getName() + " can walk " + p3.getWalkingCapability()+ "."); p3.grow(); System.out.println(p3.getName() p3.grow(); System.out.println(p3.getName() p3.grow(); System.out.println(p3.getName() System.out.println(p3.getName() p3.grow(); System.out.println(p3.getName() p3.grow(); System.out.println(p3.getName() p3.grow(); System.out.println(p3.getName() p3.grow(); System.out.println(p3.getName() p3.grow(); System.out.println(p3.getName() System.out.println(p3.getName()

+ ", " + p3.getAge() + " years old."); + ", " + p3.getAge() + " years old."); + ", " + p3.getAge() + " years old."); + " can walk " + p3.getWalkingCapability()+ "."); + ", " + p3.getAge() + " years old."); + ", " + p3.getAge() + " years old."); + ", " + p3.getAge() + " years old."); + ", " + p3.getAge() + " years old."); + ", " + p3.getAge() + " years old."); + " can walk " + p3.getWalkingCapability()+ ".");

System.out.println(p1.getName() + ", " + p1.getAge() + " years old."); p1.talk("Hello!"); p1.grow(); System.out.println(p1.getName() + ", " + p1.getAge() + " years old."); p1.talk("Hi!"); p2.eat("Apple");

!

10!

p2.eat("Bread"); p2.needFood(); p2.eat("Orange"); } }

Problem 7.

(35 points)

The Game of Nim In this part of the assignment, we will start developing a Java Object-Oriented program for the Game of Nim. We have already seen a simple, text-version of this game at the very first session. Following is a description of the game: There is a pile of some marbles and two players. The number of marbles in the pile can be between 10 and 100. The two players alternatively take marbles from one pile. In each move, a player must take at least one and at most half of the marbles. Then, the other player takes a turn. The player who takes the last marble loses the game. We consider two modes in this game. In the first mode, the computer plays against a human player. The computer can be Novice (Stupid), and in its turn just takes a random number of marbles, or it can be Smart, and in its turn uses a smart strategy to take the best number of marbles trying to win the game at the end. Note that in any case, computer will follow the game rules. In the second mode two human players can play against each other. Using the above description, your first ask is to figure out and extract all the classes required for this game. Then, for each class, find the list of its properties and methods. For each property of a class, its data type and possible values must be specified. Also, for each method its return type, if any, and parameters along with their types should be determined. After extracting all the above information, create the initial version of each class. In this phase you don’t need to write the body of the methods. Instead, inside each method, using a comment clearly explain its task, including the information it receives from the caller, its task, and the possible value it returns to the caller. Note that in the version, we don’t create a class to run the game, and we only design the essential parts of the game as one or more Java classes. Java file names: One java file for each class To give you a better idea, you can see a sample running of the game I showed you in class on the next two pages. You can see the sample solution from the code provided for assignment 2.

!

11!

!

12!

!

13!...


Similar Free PDFs