Great Deal! Get Instant $10 FREE in Account on First Order + 10% Cashback on Every Order Order Now

import org.junit.Test;import org.junit.After; import java.lang.reflect.Field; import org.junit.Assert;import org.junit.Before;import org.junit.rules.Timeout; import org.junit.runner.JUnitCore;import...

1 answer below »
import org.junit.Test;import org.junit.After;
import java.lang.reflect.Field;
import org.junit.Assert;import org.junit.Before;import org.junit.rules.Timeout;
import org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;
import javax.swing.*;import java.io.*;import java.lang.reflect.*;import java.util.ArrayList;import java.util.concurrent.ThreadLocalRandom;import java.lang.reflect.InvocationTargetException;import java.util.UUID;
import static org.junit.Assert.*;
/*** A framework to run public test cases.**

Purdue University -- CS XXXXXXXXXXSummer 2021

** @author Purdue CS* @version June 14, 2021*/public class RunLocalTest { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestCase.class); if (result.wasSuccessful()) { System.out.println("Excellent - Test ran successfully"); } else { for (Failure failure : result.getFailures()) { XXXXXXXXXXSystem.out.println(failure.toString()); } } }
/** * A set of public test cases. * *

Purdue University -- CS XXXXXXXXXXSummer 2021

* * @author Purdue CS * @version June 14, 2021 */ public static class TestCase { private final PrintStream originalOutput = System.out; private final InputStream originalSysin = System.in;
@SuppressWarnings("FieldCanBeLocal") private ByteArrayInputStream testIn;
@SuppressWarnings("FieldCanBeLocal") private ByteArrayOutputStream testOut;
@Before public void outputStart() { testOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(testOut)); }
@After public void restoreInputAndOutput() { System.setIn(originalSysin); System.setOut(originalOutput); }
private String getOutput() { return testOut.toString(); }
@SuppressWarnings("SameParameterValue") private void receiveInput(String str) { testIn = new ByteArrayInputStream(str.getBytes()); System.setIn(testIn); }
@Test(timeout = XXXXXXXXXXpublic void classDeclarationTestOne() { Class clazz = Session.class;
int modifiers = clazz.getModifiers();
Class[] superinterfaces = clazz.getInterfaces();
assertTrue("Ensure that `Session` is `public`!", Modifier.isPublic(modifiers));
assertFalse("Ensure that `Session` is NOT `abstract`!", Modifier.isAbstract(modifiers));
Assert.assertEquals("Ensure that `Session` implements no interfaces!", 0, superinterfaces.length); }
@Test(timeout = XXXXXXXXXXpublic void classDeclarationTestTwo() { Class clazz = Lab.class;
int modifiers = clazz.getModifiers();
Class[] superinterfaces = clazz.getInterfaces();
assertTrue("Ensure that `Lab` is `public`!", Modifier.isPublic(modifiers));
assertFalse("Ensure that `Lab` is NOT `abstract`!", Modifier.isAbstract(modifiers));
Assert.assertEquals("Ensure that `Lab` implements no interfaces!", 0, superinterfaces.length); } @Test(timeout = XXXXXXXXXXpublic void classDeclarationTestThree() { Class clazz = LabManager.class;
int modifiers = clazz.getModifiers();
Class[] superinterfaces = clazz.getInterfaces();
assertTrue("Ensure that `LabManager` is `public`!", Modifier.isPublic(modifiers));
assertFalse("Ensure that `LabManager` is NOT `abstract`!", Modifier.isAbstract(modifiers));
Assert.assertEquals("Ensure that `LabManager` implements no interfaces!", 0, superinterfaces.length); } @Test(timeout = XXXXXXXXXXpublic void classDeclarationTestFour() { Class clazz = TimeKeeper.class;
int modifiers = clazz.getModifiers();
Class[] superinterfaces = clazz.getInterfaces();
assertTrue("Ensure that `TimeKeeper` is `public`!", Modifier.isPublic(modifiers));
assertFalse("Ensure that `TimeKeeper` is NOT `abstract`!", Modifier.isAbstract(modifiers));
Assert.assertEquals("Ensure that `TimeKeeper` implements no interfaces!", 0, superinterfaces.length); } @Test(timeout = XXXXXXXXXXpublic void fullOutputTestOne() { try {
XXXXXXXXXXString expected = "Welcome to the TimeKeeper application!\n" + "1. Initialize Application\n" + "2. Exit\n" + "Thank you for using TimeKeeper!\n";
XXXXXXXXXXString input = "2\n"; XXXXXXXXXXreceiveInput(input); XXXXXXXXXXTimeKeeper.main(new String[0]); XXXXXXXXXXString actual = getOutput(); XXXXXXXXXXAssert.assertEquals("Ensure TimeKeeper functions as described in the handout!", expected, actual); } catch (Exception e){ XXXXXXXXXXe.printStackTrace(); XXXXXXXXXXfail(); } } @Test(timeout = XXXXXXXXXXpublic void fullOutputTestTwo() { try {
XXXXXXXXXXString expected = "Welcome to the TimeKeeper application!\n" + "1. Initialize Application\n" + "2. Exit\n" + "Invalid input. Please try again.\n" + "1. Initialize Application\n" + "2. Exit\n" + "Invalid input. Please try again.\n" + "1. Initialize Application\n" + "2. Exit\n" + "Thank you for using TimeKeeper!\n"; XXXXXXXXXXString input = "12\n99\n2\n"; XXXXXXXXXXreceiveInput(input); XXXXXXXXXXTimeKeeper.main(new String[0]); XXXXXXXXXXString actual = getOutput(); XXXXXXXXXXAssert.assertEquals("Ensure TimeKeeper functions as described in the handout!", expected, actual); } catch (Exception e){ XXXXXXXXXXe.printStackTrace(); XXXXXXXXXXfail(); } }
}}1)-

Description

For this project, you will be writing a lab management application. You will track lab reservations for three labs to help the CS department allocate space effectively.

This project is worth 7% of your final grade. We recommend that you take it, along with the other projects in the class, very seriously.

You will be implementing four classes:Session,Lab,LabManager, andTimeKeeper.

Note: 5 points of your grade is based on Coding Style. You will need to update the Starter Code to follow the standards described on Brightspace. Use the "Run" button to check your Coding Style without using a submission.


Instructions

Follow the instructions for each class.

Session.java

This class represents an individual session in a lab.

Fields

Field Name

Type

Access Modifier

Description

name

String

private

The name of the session.

enrollment

int

private

The number of attendees enrolled in this session.


Constructor

Access Modifier

Constructor Name

Input Parameters

Description

public

Session

String name, int enrollment

Construct a newly allocatedSessionobject and instantiate the fields to their respective parameters.

public

Session

None

Construct a newly allocatedSessionobject and instantiate the fields to the following:

  • name= ""
  • enrollment= 0

Methods

Method Name

Return Type

Access Modifier

Input Parameters

Description

getName

String

public

Returns thenameof thisSession.

getEnrollment

int

public

Returns theenrollmentof thisSession.

setName

void

public

String name

Sets thenameof thisSession.

setEnrollment

void

public

int enrollment

Sets theenrollmentof thisSession.

toString

String

public

None

Returns the String representation of thisSession.

For Example, given the following fields:

  • name= "CS 18000"
  • enrollment= 21

The result of callingtoString()would be:

  • Session{Name - CS 18000, Enrollment - 21}

Lab.java

This class represents the lab.

Fields

Field Name

Type

Access Modifier

Description

morning

Session

private

The morning session associated with this lab.

afternoon

Session

private

The afternoon session associated with this lab.

capacity

int

private

The room capacity of this lab.

location

String

private

The location of this lab.

Constructors:

Access Modifier

Constructor Name

Input Parameters

Description

public

Lab

Session morning,

Session afternoon,

int capacity,

String location

Construct a newly allocatedLabobject and instantiate the fields to the specified parameters.

public

Lab

int capacity,

String location

Construct a newly allocatedLabobject and instantiate the fields to the specified parameters.

Instantiate the two Session fields by calling the Session constructor with no parameters.

Methods:

Method Name

Return Type

Access Modifier

Input

Parameters

Description

getMorning

Session

public

None

Returns themorningsession of thisLab.

getAfternoon

Session

public

None

Returns theafternoonsession of thisLab.

getCapacity

int

public

None

Returns thecapacityof thisLab.

getLocation

String

public

None

Returns thelocationof thisLab.

setMorning

void

public

Session morning

Sets themorningsession of thisLab.

setAfternoon

void

public

Session afternoon

Sets theafternoonsession of thisLab.

setCapacity

void

public

int capacity

Sets thecapacityof thisLab.

setLocation

void

public

String location

Sets thelocationof thisLab.

listAvailabilities

String

public

None

Returns a String that documents the available sessions for this lab.

If the morning is available, add "Morning: Available\n" to the String.

If the afternoon is available, add "Afternoon: Available\n" to the String.

If no session is available, return "No Availabilities".

Note: If both sessions are available, be sure to include each in the returned String.

Note: A session is considered available if the enrollment is 0.

listReservations

String

public

None

Returns a String that documents the reserved sessions for this lab.

If the morning is reserved, add "Morning: Reserved\n" to the String.

If the afternoon is reserved, add "Afternoon: Reserved\n" to the String.

If no session is reserved, return "No Reservations".

Note: If both sessions are reserved, be sure to include each in the returned String.

Note: A session is considered reserved if the enrollment is greater than 0.

toString

String

public

None

Returns the String representation of thisLab.

For Example, given the following fields:

  • capacity= 25
  • location= "LWSN B148"
  • morning= Session{Name - CS 18000, Enrollment - 21}
  • afternoon= Session{Name - "", Enrollment - 0}

The result of callingtoString()would be:

  • Lab{Capacity - 25, Location - LWSN B148, Morning: Session{Name - CS 18000, Enrollment - 21}, Afternoon: Available}

Note: If a session is not reserved for either of the available times, do not include the toString for that session. Instead, add "Available".

LabManager.java

LabManager includes the three labs that you will need to manage. Additionally, it will have several methods that will be useful for the user interface.

Note: You must create each of the classes and implement them as described in their respective sections. Failure to do so will negatively impact your score.

Fields

Field Name

Type

Access Modifier

Description

labOne

Lab

private

The first lab of thisLabManager.

labTwo

Lab

private

The second lab of thisLabManager.

labThree

Lab

private

The third lab of thisLabManager.


Constructor

Access Modifier

Constructor Name

Input Parameters

Description

public

LabManager

Lab labOne,

Lab labTwo,

Lab labThree

Construct a newly allocatedLabManagerobject and instantiate the fields to their respective parameters.

Methods

Method Name

Return Type

Access Modifier

Input Parameters

Description

getLabOne

Lab

public

None

Returns the first lab of thisLabManager.

getLabTwo

Lab

public

None

Returns the second lab of thisLabManager.

getLabThree

Lab

public

None

Returns the third lab of thisLabManager.

setLabOne

void

public

Lab labOne

Sets the first lab of thisLabManager.

setLabTwo

void

public

Lab labTwo

Sets the second lab of thisLabManager.

setLabThree

void

public

Lab labThree

Sets the third lab of thisLabManager.

calculateTotalCapacity

int

public

None

Returns the total capacity for all three labs. The total capacity is the maximum number of seats occupied if every session for all three labs is booked at full capacity.

For the following three labs:

  • labOne
    • Capacity: 25
    • Morning: 20
    • Afternoon: 14
  • labTwo
    • Capacity: 20
    • Morning: 20
    • Afternoon: 15
  • labThree
    • Capacity: 36
    • Morning: 31
    • Afternoon: 32

The result of calling calculateTotalCapacity would be 162.

calculateTotalUtilization

double

public

None

Returns the average percentage utilization for all three labs. This is the percentage of seats occupied overall out of the total seats available.

For example, if labOne has an enrollment of 20 in the morning and 14 in the afternoon, with a capacity of 25, the average utilization for the lab is XXXXXXXXXX%). This method calculates the total average utilization for all three labs combined.

For the following three labs:

  • labOne
    • Capacity: 25
    • Morning: 20
    • Afternoon: 14
  • labTwo
    • Capacity: 20
    • Morning: 20
    • Afternoon: 15
  • labThree
    • Capacity: 36
    • Morning: 31
    • Afternoon: 32

The result of calling calculateTotalUtilization would be 0.81.

calculateAvailableSeats

int

public

None

Returns the total number of available seats for all three labs.

If a session is not reserved, the available seats for that session are the lab capacity. If a session is reserved, the available seats would be the lab capacity minus the enrollment.

For the following three labs:

  • labOne
    • Capacity: 25
    • Morning: 20
    • Afternoon: 14
  • labTwo
    • Capacity: 20
    • Morning: 20
    • Afternoon: 15
  • labThree
    • Capacity: 36
    • Morning: 31
    • Afternoon: 32

The result of calling calculateAvailableSeats would be 30.

listReservedLabs

String

public

None

List the reservations for each lab.

For example, if each of the morning sessions are reserved, the output would be as follows:

Lab One
Morning: Reserved

Lab Two
Morning: Reserved

Lab Three
Morning: Reserved

If a lab has no reservations, the "No Reservations" message should be used instead. For example, if no lab has any reservations, the output would be as follows:

Lab One
No Reservations

Lab Two
No Reservations

Lab Three
No Reservations

listAvailableLabs

String

public

None

List the availabilities for each lab.

For example, if each of the morning sessions are reserved, the output would be as follows:

Lab One
Afternoon: Available

Lab Two
Afternoon: Available

Lab Three
Afternoon: Available

If a lab has no availabilities, the "No Availabilities" message should be used instead. For example, if no lab has any availabilities, the output would be as follows:

Lab One
No Availabilities

Lab Two
No Availabilities

Lab Three
No Availabilities

addReservation

String

public

String location,

String time,

String name,

int enrollment

Adds a reservation for the lab at the specified location and time. Returns a message depending on the outcome of the operation.

Potential returns:

  • Success - "Reservation added!"
  • Enrollment is greater than capacity - "Error. Capacity exceeded"
  • Time is invalid or already reserved - "Error. Invalid time."
  • Location is invalid - "Error. Invalid location"

A successful operation updates the session at the specified time and location with the name and enrollment provided. No changes occur if there is an error.

removeReservation

String

public

String location,

String time

Removes a reservation for the lab at the specified location and time. Returns a message depending on the outcome of the operation.

Potential returns:

  • Success - "Reservation removed!"
  • Time is invalid or was not reserved - "Error. Invalid time."
  • Location is invalid - "Error. Invalid location"

A successful operation removes the session at the specified time and location by changing the name to "" and enrollment to 0. No changes occur if there is an error.

modifyReservation

String

public

String location,

String time,

String name,

int enrollment

Modifies a reservation for the lab at the specified location and time. Returns a message depending on the outcome of the operation.

Potential returns:

  • Success - "Reservation modified!"
  • Enrollment is greater than capacity - "Error. Capacity exceeded"
  • Time is invalid or was not reserved - "Error. Invalid time."
  • Location is invalid - "Error. Invalid location"

A successful operation updates the session at the specified time and location with the name and enrollment provided. No changes occur if there is an error.

toString

String

public

None

Returns the String representation of thisLabManager.

For Example, given the following fields:

  • labOne= Lab{Capacity - 25, Location - LWSN B146, Morning: Session{Name - CS 18000, Enrollment - 21}, Afternoon: Available}
  • labTwo= Lab{Capacity - 22, Location - LWSN B148, Morning: Session{Name - CS 24000, Enrollment - 19}, Afternoon: Available}
  • labThree= Lab{Capacity - 24, Location - LWSN B158, Morning: Session{Name - CS 25100, Enrollment - 23}, Afternoon: Available}

The result of callingtoString()would be:

  • LabManager{Lab{Capacity - 25, Location - LWSN B146, Morning: Session{Name - CS 18000, Enrollment - 21}, Afternoon: Available}, Lab{Capacity - 22, Location - LWSN B148, Morning: Session{Name - CS 24000, Enrollment - 19}, Afternoon: Available}, Lab{Capacity - 24, Location - LWSN B158, Morning: Session{Name - CS 25100, Enrollment - 23}, Afternoon: Available}}

TimeKeeper.java

TimeKeeper includes the several menus for the user to navigate as they manage the labs. The implementation details are up to you, but we recommend that you utilize the methods we require for the other classes. You are also welcome to add additional methods, provided your solution still meets the specifications provided above.

There are three menus in the TimeKeeper application: initialization, ongoing, and statistics. Each will be discussed separately below.

Note: Brackets [] indicate input.

Initialization Menu

This menu runs immediately following the program welcome message. It prompts the user to enter the lab details. This information should be used to initialize the labs in LabManager.

Sample Output 1

Welcome to the TimeKeeper application!
1. Initialize Application
2. Exit
[1] Enter the capacity for Lab 1: [25] Enter the location for Lab 1: [LWSN B158] Enter the capacity for Lab 2: [24] Enter the location for Lab 2: [LWSN B148] Enter the capacity for Lab 3: [22] Enter the location for Lab 3: [HAAS G040]

Is the user elects to exit, print the exit message and end the program.

Sample Output 2

Welcome to the TimeKeeper application! 1. Initialize Application 2. Exit [2] Thank you for using TimeKeeper!

If the user enters an invalid input, print the error message and reprint the menu.

Sample Output 3

Welcome to the TimeKeeper application! 1. Initialize Application 2. Exit [3] Invalid input. Please try again. 1. Initialize Application 2. Exit [2] Thank you for using TimeKeeper!

Ongoing Menu & Statistics Menu

The Ongoing Menu controls the main application features after initialization. Each option corresponds to functionality in the other classes. We recommend that you consider ways to optimize your code while developing the solution. We've included the expected output for each menu option as samples below.

Note: Sample Output in this section is truncated to remove the initialization menu portion. You may assume that it immediately precedes any sample. You may also assume that the output is all from the same run (modifications persist between sections).

Sample Output 1

1. View Current Lab Schedule
2. List Labs by Availability
3. List Labs by Reservation
4. Add a Reservation
5. Remove a Reservation
6. Modify a Reservation
7. Calculate Statistics
8. Exit
[1]
Lab{Capacity - 22, Location - LWSN B158, Morning: Available, Afternoon: Available} Lab{Capacity - 22, Location - LWSN B148, Morning: Available, Afternoon: Available} Lab{Capacity - 16, Location - HAAS G040, Morning: Available, Afternoon: Available} 1. View Current Lab Schedule 2. List Labs by Availability 3. List Labs by Reservation 4. Add a Reservation 5. Remove a Reservation 6. Modify a Reservation 7. Calculate Statistics 8. Exit

Sample Output 2

1. View Current Lab Schedule 2. List Labs by Availability 3. List Labs by Reservation 4. Add a Reservation 5. Remove a Reservation 6. Modify a Reservation 7. Calculate Statistics 8. Exit [2] Lab One Morning: Available Afternoon: Available  Lab Two Morning: Available Afternoon: Available  Lab Three Morning: Available Afternoon: Available

Sample Output 3

1. View Current Lab Schedule 2. List Labs by Availability 3. List Labs by Reservation 4. Add a Reservation 5. Remove a Reservation 6. Modify a Reservation 7. Calculate Statistics 8. Exit [3] Lab One No Reservations  Lab Two No Reservations  Lab Three No Reservations 

Sample Output 4

1. View Current Lab Schedule 2. List Labs by Availability 3. List Labs by Reservation 4. Add a Reservation 5. Remove a Reservation 6. Modify a Reservation 7. Calculate Statistics 8. Exit [4] Enter the location of the lab: [LWSN B158] Enter the time of the reservation: [morning] Enter the name of the reservation: [CS 18000] Enter the expected enrollment: [18] Reservation added!
1. View Current Lab Schedule
2. List Labs by Availability
3. List Labs by Reservation
4. Add a Reservation
5. Remove a Reservation
6. Modify a Reservation
7. Calculate Statistics
8. Exit
[4]
Enter the location of the lab:
[LWSN B158]
Enter the time of the reservation:
[afternoon]
Enter the name of the reservation:
[CS 24000]
Enter the expected enrollment:
[20]
Reservation added!

Sample Output 5

1. View Current Lab Schedule 2. List Labs by Availability 3. List Labs by Reservation 4. Add a Reservation 5. Remove a Reservation 6. Modify a Reservation 7. Calculate Statistics 8. Exit [5] Enter the location of the lab: [LWSN B158] Enter the time of the reservation: [afternoon] Reservation removed!

Sample Output 6

1. View Current Lab Schedule 2. List Labs by Availability 3. List Labs by Reservation 4. Add a Reservation 5. Remove a Reservation 6. Modify a Reservation 7. Calculate Statistics 8. Exit [6] Enter the location of the lab: [LWSN B158] Enter the time of the reservation: [morning] Enter the updated name of the reservation: [CS 25100] Enter the updated enrollment: [12] Reservation updated!

Sample Output 7

Sample Output 7 includes the statistics menu. Each of the options prints the results of a different calculation.

1. View Current Lab Schedule 2. List Labs by Availability 3. List Labs by Reservation 4. Add a Reservation 5. Remove a Reservation 6. Modify a Reservation 7. Calculate Statistics 8. Exit [7] 1. Total Capacity 2. Total Utilization 3. Available seats 4. Return to main menu [1] Total Capacity: XXXXXXXXXXTotal Capacity 2. Total Utilization 3. Available seats 4. Return to main menu [2] Total Utilization: XXXXXXXXXXTotal Capacity 2. Total Utilization 3. Available seats 4. Return to main menu [3] Available seats: XXXXXXXXXXTotal Capacity 2. Total Utilization 3. Available seats 4. Return to main menu [4]

Sample Output 8

1. View Current Lab Schedule 2. List Labs by Availability 3. List Labs by Reservation 4. Add a Reservation 5. Remove a Reservation 6. Modify a Reservation 7. Calculate Statistics 8. Exit [8] Thank you for using TimeKeeper!

Sample Output 9

1. View Current Lab Schedule 2. List Labs by Availability 3. List Labs by Reservation 4. Add a Reservation 5. Remove a Reservation 6. Modify a Reservation 7. Calculate Statistics 8. Exit [12] Invalid input. Please try again.

Additional Notes:

  • The starter code provided for TimeKeeper.java provides String constants that can be used for the prompts.

  • Text input should be compared without regard to case.
  • For additional output examples, review the expected return values from the other class methods. For example, the various error messages available when adding or modifying a reservation.
  • Invalid input may occur at any point. Be sure to handle it and print either the menu error message or the ones included in the methods!
  • All double values should be formatted to two decimal places.

Testing

We have included a program that will allow you to create and run output tests automatically in the Starter Code. This will make it easier for you to verify that each possible progression through your solution is correct. Take a look atRunLocalTest.java. There are many utility features and tools that you do not need to worry about at the moment, instead, focus on the test case. It is included in the Starter Code. Read through it.

You can modify the test to test any method you like by following the same format. You can either download the program and run the main method or use the "Run" button on Vocareum to run the test. You can repeat this process for each path.

Public Test Cases Note

For many homeworks and projects, we will give you test cases that correspond to several of the ways we will be testing your program. But, we will not give you test cases for ALL of the ways we will be testing your program. You should think of other test cases to use that will fully test every aspect of every feature of your program. Just because your program passes all the test cases we give you does not mean that it is fully correct and will receive a score of 100.


Submit

After testing your solution and verifying that it meets the requirements described in this document, you can submit on Vocareum. You have 10 submission attempts to achieve full points.

Starter code-

import org.junit.Test;

import org.junit.After;


import java.lang.reflect.Field;


import org.junit.Assert;

import org.junit.Before;

import org.junit.rules.Timeout;


import org.junit.runner.JUnitCore;

import org.junit.runner.Result;

import org.junit.runner.notification.Failure;


import javax.swing.*;

import java.io.*;

import java.lang.reflect.*;

import java.util.ArrayList;

import java.util.concurrent.ThreadLocalRandom;

import java.lang.reflect.InvocationTargetException;

import java.util.UUID;


import static org.junit.Assert.*;


/**

* A framework to run public test cases.

*

*

Purdue University -- CS XXXXXXXXXXSummer 2021

*

* @author Purdue CS

* @version June 14, 2021

*/

public class RunLocalTest {

public static void main(String[] args) {

Result result = JUnitCore.runClasses(TestCase.class);

if (result.wasSuccessful()) {

System.out.println("Excellent - Test ran successfully");

} else {

for (Failure failure : result.getFailures()) {

XXXXXXXXXXSystem.out.println(failure.toString());

}

}

}


/**

* A set of public test cases.

*

*

Purdue University -- CS XXXXXXXXXXSummer 2021

*

* @author Purdue CS

* @version June 14, 2021

*/

public static class TestCase {

private final PrintStream originalOutput = System.out;

private final InputStream originalSysin = System.in;


@SuppressWarnings("FieldCanBeLocal")

private ByteArrayInputStream testIn;


@SuppressWarnings("FieldCanBeLocal")

private ByteArrayOutputStream testOut;


@Before

public void outputStart() {

testOut = new ByteArrayOutputStream();

System.setOut(new PrintStream(testOut));

}


@After

public void restoreInputAndOutput() {

System.setIn(originalSysin);

System.setOut(originalOutput);

}


private String getOutput() {

return testOut.toString();

}


@SuppressWarnings("SameParameterValue")

private void receiveInput(String str) {

testIn = new ByteArrayInputStream(str.getBytes());

System.setIn(testIn);

}


@Test(timeout = 1000)

public void classDeclarationTestOne() {

Class clazz = Session.class;


int modifiers = clazz.getModifiers();


Class[] superinterfaces = clazz.getInterfaces();


assertTrue("Ensure that `Session` is `public`!", Modifier.isPublic(modifiers));


assertFalse("Ensure that `Session` is NOT `abstract`!", Modifier.isAbstract(modifiers));


Assert.assertEquals("Ensure that `Session` implements no interfaces!", 0, superinterfaces.length);

}


@Test(timeout = 1000)

public void classDeclarationTestTwo() {

Class clazz = Lab.class;


int modifiers = clazz.getModifiers();


Class[] superinterfaces = clazz.getInterfaces();


assertTrue("Ensure that `Lab` is `public`!", Modifier.isPublic(modifiers));


assertFalse("Ensure that `Lab` is NOT `abstract`!", Modifier.isAbstract(modifiers));


Assert.assertEquals("Ensure that `Lab` implements no interfaces!", 0, superinterfaces.length);

}

@Test(timeout = 1000)

public void classDeclarationTestThree() {

Class clazz = LabManager.class;


int modifiers = clazz.getModifiers();


Class[] superinterfaces = clazz.getInterfaces();


assertTrue("Ensure that `LabManager` is `public`!", Modifier.isPublic(modifiers));


assertFalse("Ensure that `LabManager` is NOT `abstract`!", Modifier.isAbstract(modifiers));


Assert.assertEquals("Ensure that `LabManager` implements no interfaces!", 0, superinterfaces.length);

}

@Test(timeout = 1000)

public void classDeclarationTestFour() {

Class clazz = TimeKeeper.class;


int modifiers = clazz.getModifiers();


Class[] superinterfaces = clazz.getInterfaces();


assertTrue("Ensure that `TimeKeeper` is `public`!", Modifier.isPublic(modifiers));


assertFalse("Ensure that `TimeKeeper` is NOT `abstract`!", Modifier.isAbstract(modifiers));


Assert.assertEquals("Ensure that `TimeKeeper` implements no interfaces!", 0, superinterfaces.length);

}

@Test(timeout = 1000)

public void fullOutputTestOne() {

try {


XXXXXXXXXXString expected = "Welcome to the TimeKeeper application!\n" +

"1. Initialize Application\n" +

"2. Exit\n" +

"Thank you for using TimeKeeper!\n";


XXXXXXXXXXString input = "2\n";

XXXXXXXXXXreceiveInput(input);

XXXXXXXXXXTimeKeeper.main(new String[0]);

XXXXXXXXXXString actual = getOutput();

XXXXXXXXXXAssert.assertEquals("Ensure TimeKeeper functions as described in the handout!", expected, actual);

} catch (Exception e){

XXXXXXXXXXe.printStackTrace();

XXXXXXXXXXfail();

}

}

@Test(timeout = 1000)

public void fullOutputTestTwo() {

try {


XXXXXXXXXXString expected = "Welcome to the TimeKeeper application!\n" +

"1. Initialize Application\n" +

"2. Exit\n" +

"Invalid input. Please try again.\n" +

"1. Initialize Application\n" +

"2. Exit\n" +

"Invalid input. Please try again.\n" +

"1. Initialize Application\n" +

"2. Exit\n" +

"Thank you for using TimeKeeper!\n";

XXXXXXXXXXString input = "12\n99\n2\n";

XXXXXXXXXXreceiveInput(input);

XXXXXXXXXXTimeKeeper.main(new String[0]);

XXXXXXXXXXString actual = getOutput();

XXXXXXXXXXAssert.assertEquals("Ensure TimeKeeper functions as described in the handout!", expected, actual);

} catch (Exception e){

XXXXXXXXXXe.printStackTrace();

XXXXXXXXXXfail();

}

}


}

}

import org.junit.Test;import org.junit.After;
import java.lang.reflect.Field;
import org.junit.Assert;import org.junit.Before;import org.junit.rules.Timeout;
import org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;
import javax.swing.*;import java.io.*;import java.lang.reflect.*;import java.util.ArrayList;import java.util.concurrent.ThreadLocalRandom;import java.lang.reflect.InvocationTargetException;import java.util.UUID;
import static org.junit.Assert.*;
/*** A framework to run public test cases.**

Purdue University -- CS XXXXXXXXXXSummer 2021

** @author Purdue CS* @version June 14, 2021*/public class RunLocalTest { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestCase.class); if (result.wasSuccessful()) { System.out.println("Excellent - Test ran successfully"); } else { for (Failure failure : result.getFailures()) { XXXXXXXXXXSystem.out.println(failure.toString()); } } }
/** * A set of public test cases. * *

Purdue University -- CS XXXXXXXXXXSummer 2021

* * @author Purdue CS * @version June 14, 2021 */ public static class TestCase { private final PrintStream originalOutput = System.out; private final InputStream originalSysin = System.in;
@SuppressWarnings("FieldCanBeLocal") private ByteArrayInputStream testIn;
@SuppressWarnings("FieldCanBeLocal") private ByteArrayOutputStream testOut;
@Before public void outputStart() { testOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(testOut)); }
@After public void restoreInputAndOutput() { System.setIn(originalSysin); System.setOut(originalOutput); }
private String getOutput() { return testOut.toString(); }
@SuppressWarnings("SameParameterValue") private void receiveInput(String str) { testIn = new ByteArrayInputStream(str.getBytes()); System.setIn(testIn); }
@Test(timeout = XXXXXXXXXXpublic void classDeclarationTestOne() { Class clazz = Session.class;
int modifiers = clazz.getModifiers();
Class[] superinterfaces = clazz.getInterfaces();
assertTrue("Ensure that `Session` is `public`!", Modifier.isPublic(modifiers));
assertFalse("Ensure that `Session` is NOT `abstract`!", Modifier.isAbstract(modifiers));
Assert.assertEquals("Ensure that `Session` implements no interfaces!", 0, superinterfaces.length); }
@Test(timeout = XXXXXXXXXXpublic void classDeclarationTestTwo() { Class clazz = Lab.class;
int modifiers = clazz.getModifiers();
Class[] superinterfaces = clazz.getInterfaces();
assertTrue("Ensure that `Lab` is `public`!", Modifier.isPublic(modifiers));
assertFalse("Ensure that `Lab` is NOT `abstract`!", Modifier.isAbstract(modifiers));
Assert.assertEquals("Ensure that `Lab` implements no interfaces!", 0, superinterfaces.length); } @Test(timeout = XXXXXXXXXXpublic void classDeclarationTestThree() { Class clazz = LabManager.class;
int modifiers = clazz.getModifiers();
Class[] superinterfaces = clazz.getInterfaces();
assertTrue("Ensure that `LabManager` is `public`!", Modifier.isPublic(modifiers));
assertFalse("Ensure that `LabManager` is NOT `abstract`!", Modifier.isAbstract(modifiers));
Assert.assertEquals("Ensure that `LabManager` implements no interfaces!", 0, superinterfaces.length); } @Test(timeout = XXXXXXXXXXpublic void classDeclarationTestFour() { Class clazz = TimeKeeper.class;
int modifiers = clazz.getModifiers();
Class[] superinterfaces = clazz.getInterfaces();
assertTrue("Ensure that `TimeKeeper` is `public`!", Modifier.isPublic(modifiers));
assertFalse("Ensure that `TimeKeeper` is NOT `abstract`!", Modifier.isAbstract(modifiers));
Assert.assertEquals("Ensure that `TimeKeeper` implements no interfaces!", 0, superinterfaces.length); } @Test(timeout = XXXXXXXXXXpublic void fullOutputTestOne() { try {
XXXXXXXXXXString expected = "Welcome to the TimeKeeper application!\n" + "1. Initialize Application\n" + "2. Exit\n" + "Thank you for using TimeKeeper!\n";
XXXXXXXXXXString input = "2\n"; XXXXXXXXXXreceiveInput(input); XXXXXXXXXXTimeKeeper.main(new String[0]); XXXXXXXXXXString actual = getOutput(); XXXXXXXXXXAssert.assertEquals("Ensure TimeKeeper functions as described in the handout!", expected, actual); } catch (Exception e){ XXXXXXXXXXe.printStackTrace(); XXXXXXXXXXfail(); } } @Test(timeout = XXXXXXXXXXpublic void fullOutputTestTwo() { try {
XXXXXXXXXXString expected = "Welcome to the TimeKeeper application!\n" + "1. Initialize Application\n" + "2. Exit\n" + "Invalid input. Please try again.\n" + "1. Initialize Application\n" + "2. Exit\n" + "Invalid input. Please try again.\n" + "1. Initialize Application\n" + "2. Exit\n" + "Thank you for using TimeKeeper!\n"; XXXXXXXXXXString input = "12\n99\n2\n"; XXXXXXXXXXreceiveInput(input); XXXXXXXXXXTimeKeeper.main(new String[0]); XXXXXXXXXXString actual = getOutput(); XXXXXXXXXXAssert.assertEquals("Ensure TimeKeeper functions as described in the handout!", expected, actual); } catch (Exception e){ XXXXXXXXXXe.printStackTrace(); XXXXXXXXXXfail(); } }
}}2)-

Description

For this Homework, you will be writing two classes: Loan and LendingCalculator. These classes will help a user determine their repayment options for potential loans.

Note: This assignment greatly simplifies the calculations and analysis required for these situations. Do not use your solution for real-world financial decisions!

Note: 5 points of your Challenge grade is based on Coding Style. You will need to follow the standards described on Brightspace.Use the "Run" button to check your Coding Style without using a submission.


Instructions

The implementation instructions are documented below.Note: Functionality descriptions are exact. That is, if a method performs some calculation, your program must implement that calculation within the method. If you implement it elsewhere, such as in the main method or a different class, you will not receive credit.

Loan

This class contains attributes associated with a specific loan.

Fields

NameTypeModifiersDescription
durationintprivateThe length of the loan in months.
ratedoubleprivateThe annual percentage interest of the loan.
amountdoubleprivateThe total amount of the loan.
monthlyPaymentdoubleprivateThe monthly payment of the loan.

Constructor

ParametersModifierDescription
int duration, double rate, double amountpublic

Instantiate the class fields to their associated parameters.

Call the

calculateMonthlyPayment

method to instantiate the

monthlyPaymentfield. The implementation details are below.

Methods

NameReturn TypeParametersModifierDescription
getDurationintNonepublicReturns the duration of the loan.
getRatedoubleNonepublicReturns the rate of the loan.
getAmountdoubleNonepublicReturns the amount of the loan.
setDurationvoidint durationpublicSets the duration of a loan.
setRatevoiddouble ratepublicSets the rate of a loan.
setAmountvoiddouble amountpublicSets the amount of a loan.
calculateMonthlyPaymentdoubleNonepublicCalculate and return the monthly payment using the formula in the next section.
calculateTotalInterestdoubleboolean outputpublic

Calculate and return the total interest paid using the formula in the next section.

Ifoutputis true, print the amortization table as part of the calculation. Ifoutputis false, only return the calculated value.

toStringStringNonepublicReturn a String formatted according to the specification in the next section.

Monthly Payment Calculation

Monthly Payment =amount*((rate/ 12)* (1 +rate/ 12)duration) / ((1 +rate/ 12)duration- 1 )

Hint: You'll need to find a way to do exponential calculations. Math.pow() will be useful!

Total Interest Calculation

Calculating the total loan interest may seem complex at first, but the actual math is quite simple. We will generate an amortization table to help us track the individual values. This is a formatted statement that tracks the amount of principal and interest paid with each loan payment, along with the current balance.

Interest is calculated on a monthly basis. We can find the interest charged each month by multiplying the current balance by the monthly interest rate (annual rate / 12). To find the amount of the monthly payment that is applied to the balance of the loan, just substract the monthly interest from the payment amount.

Thus, for the total Interest calculation, we have the following values:

  1. Monthly Payment: (calculated in the previous section).
  2. Payment Number: Incremented by one with every iteration.
  3. Principal: (calculated by subtracting the monthly interest from the monthly payment).
  4. Interest: (calculated by multiplying the current balance by the monthly rate).
  5. Remaining: (calculated by subtracting the principal from the current balance).

Here's an example:

Assume the loan has an initial balance of 1,000, interest rate of 12%, and duration of 12.This will result in a monthly payment of 88.85.

Payment: 1 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 921.15
Payment: 2 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 841.51
Payment: 3 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 761.08
Payment: 4 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 679.84
Payment: 5 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 597.79
Payment: 6 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 514.92
Payment: 7 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 431.22
Payment: 8 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 346.68
Payment: 9 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 261.30
Payment: 10 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 175.07
Payment: 11 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 87.97
Payment: 12 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 0.00

The total interest paid in this case would be 66.19.

toString Format

Include the following information in your toString implementation: Amount, Rate, Duration, and Payment.

For example, given the following fields values:

  • amount = XXXXXXXXXX
  • rate = 0.12
  • duration = 12
  • monthlyPayment = 88.85

The corresponding toString output would be as follows:

"Amount: XXXXXXXXXXRate: XXXXXXXXXXDuration: 12 - Payment: 88.85".

Be sure to follow this formatting exactly! All doubles should be formatted to two decimal places.

LendingCalculator

This class includes a menu for the user to interact with various loan options. The menu should loop until the user decides to quit. This menu should be in a main method, but we encourage you to utilize additional methods to simplify processing.

Menu

There are two stages to the menu operations: Initial and Ongoing.

In the initial stage, the user can select to either quit or add a loan. If they add a loan, the program prompts them to enter the details and prints a summary. After doing so, the menu switches to the ongoing interface. If the user selects to quit, the program prints a farewell message and exits.

In the ongoing stage, the user can select to quit, modify a loan, and calculate total interest. If the user modifies a loan, the same processing for adding a loan will take place. If the user selects to calculate total interest, they will choose whether or not they would like the amortization table printed before receiving the output. If the user selects to quit, the program prints a farewell message and exits.

Output

Each of the potential selections is included as sample output below.

Sample 1
Welcome to the Lending Calculator!
Menu
0. Quit
1. Add a loan
[0]
Thank you!
Sample 2
Welcome to the Lending Calculator!
Menu
0. Quit
1. Add a loan
[1]
Enter the duration:
[12]
Enter the rate:
[0.12]
Enter the amount:
[1000]
Amount: XXXXXXXXXXRate: XXXXXXXXXXDuration: 12 - Payment: 88.85
Menu
0. Quit
1. Modify Loan
2. Calculate Total Interest
[0]
Thank you!
Sample 3
Welcome to the Lending Calculator!
Menu
0. Quit
1. Add a loan
[1]
Enter the duration:
[12]
Enter the rate:
[0.12]
Enter the amount:
[1000]
Amount: XXXXXXXXXXRate: XXXXXXXXXXDuration: 12 - Payment: 88.85
Menu
0. Quit
1. Modify Loan
2. Calculate Total Interest
[1]
Enter the duration:
[24]
Enter the rate:
[0.06]
Enter the amount:
[2000]
Amount: XXXXXXXXXXRate: XXXXXXXXXXDuration: 24 - Payment: 88.64
Menu
0. Quit
1. Modify Loan
2. Calculate Total Interest
[0]
Thank you!
Sample 4
Welcome to the Lending Calculator!
Menu
0. Quit
1. Add a loan
[1]
Enter the duration:
[12]
Enter the rate:
[0.12]
Enter the amount:
[1000]
Amount: XXXXXXXXXXRate: XXXXXXXXXXDuration: 12 - Payment: 88.85
Menu
0. Quit
1. Modify Loan
2. Calculate Total Interest
[2]
Would you like to print the amortization schedule?
1. Yes
2. No
[1]
Payment: 1 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 921.15
Payment: 2 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 841.51
Payment: 3 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 761.08
Payment: 4 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 679.84
Payment: 5 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 597.79
Payment: 6 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 514.92
Payment: 7 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 431.22
Payment: 8 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 346.68
Payment: 9 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 261.30
Payment: 10 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 175.07
Payment: 11 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 87.97
Payment: 12 - Principal: XXXXXXXXXXInterest: XXXXXXXXXXRemaining: 0.00
Total Interest: 66.19
Menu
0. Quit
1. Modify Loan
2. Calculate Total Interest
[0]
Thank you!

Sample 5

Welcome to the Lending Calculator!
Menu
0. Quit
1. Add a loan
[1]
Enter the duration:
[12]
Enter the rate:
[0.12]
Enter the amount:
[1000]
Amount: XXXXXXXXXXRate: XXXXXXXXXXDuration: 12 - Payment: 88.85
Menu
0. Quit
1. Modify Loan
2. Calculate Total Interest
[2]
Would you like to print the amortization schedule?
1. Yes
2. No
[2]
Total Interest: 66.19
Menu
0. Quit
1. Modify Loan
2. Calculate Total Interest
[0]
Thank you!

Note: Brackets [] indicate input.
Note: All print statements involving doubles should be formatted to two decimal places.

Testing

We have included a program that will allow you to create and run output tests automatically in the Starter Code. This will make it easier for you to verify that each possible progression through your solution is correct. Take a look atRunLocalTest.java. There are many utility features and tools that you do not need to worry about at the moment, instead, focus on the test case. It is included in the Starter Code. Read through it.

You can modify the test to test any method you like by following the same format. You can either download the program and run the main method or use the "Run" button on Vocareum to run the test. You can repeat this process for each path.

You can also use the testing strategy from the walkthrough.

Public Test Cases Note

For many homeworks and projects, we will give you test cases that correspond to several of the ways we will be testing your program. But, we will not give you test cases for ALL of the ways we will be testing your program. You should think of other test cases to use that will fully test every aspect of every feature of your program. Just because your program passes all the test cases we give you does not mean that it is fully correct and will receive a score of 100.


Submit

After testing your solution and verifying that it meets the requirements described in this document, you can submit on Vocareum. You have 10 submission attempts to achieve full points.

Starter code-

public class LendingCalculator {

private static String welcomeMessage = "Welcome to the Lending Calculator!";

private static String menu = "Menu";

private static String initialMenu = "0. Quit\n1. Add a loan";

private static String ongoingMenu = "0. Quit\n1. Modify Loan\n2. Calculate Total Interest";

private static String exitMessage = "Thank you!";

private static String durationMessage = "Enter the duration:";

private static String rateMessage = "Enter the rate:";

private static String amountMessage = "Enter the amount:";

private static String amortizationPrompt = "Would you like to print the amortization schedule?";

private static String amortizationMenu = "1. Yes\n2. No";

private static String totalInterestMessage = "Total Interest: ";

private static String errorMessage = "Error! Invalid input.";

}


Answered 14 days After Oct 07, 2021

Solution

Saima answered on Oct 21 2021
127 Votes
LendingCalculato
LendingCalculator.zip
LendingCalculato
.classpath

    
        
            
        
    
    
    
LendingCalculato
.project

     LendingCalculato
    
    
    
    
        
             org.eclipse.jdt.core.javabuilde
            
            
        
    
    
        ...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here