Questions
You are going to make an advanced ATM program When you run the program, it will...

You are going to make an advanced ATM program

When you run the program, it will ask you if you want to:

  1. Either log in or make a new user

  2. Exit

Once I have logged in, I will have 3 balances, credit, checking, and savings. From here it will ask which account to use.

Once the account is picked they can deposit, withdraw, check balance, or log out.

Each time the user performs one of these actions, it will loop back and ask them for another action, until the Logout

(Hint: Make sure they can’t withdraw too much money)

Submission name: Advanced_ATM.py

In: Computer Science

Draw the ER diagram for the following: Emerging Electric wishes to create a database with the...

Draw the ER diagram for the following:

  1. Emerging Electric wishes to create a database with the following entities and attributes: (10)

• Customer, with attributes Customer ID, Name, Address (Street, City, State, Zip Code), and Telephone

• Location, with attributes Location ID, Address (Street, City, State, Zip Code), and Type (values of Business or Residential)

• Rate, with attributes Rate Class and RatePerKWH After interviews with the owners, you have come up with the following business rules:

• Customers can have one or more locations.

• Each location can have one or more rates, depending on the time of day.

Draw an ERD for this situation and place minimum and maximum cardinalities on the diagram. State any assumptions that you have made.

In: Computer Science

Assignment 3 - Enhanced Employee Hierarchy For this assignment, you are going to enhance the Employee...

Assignment 3 - Enhanced Employee Hierarchy

For this assignment, you are going to enhance the Employee Hierarchy that you created in Programming Assignment 2 by adding an interface called Compensation with the following two methods:

  • earnings() - receives no parameters and returns a double.
  • raise(double percent) - receives one parameter which is the percentage of the raise and returns a void.

Create the abstract class CompensationModel which implements the Compensation interface. Create the following classes as subclasses of CompensationModel:

  • SalariedCompensationModel - For Employees who are paid a fixed weekly salary, this class should contain a weeklySalary instance variable, and should implement methods earnings() to return the weekly salary, and raise(double percent) which increases the weekly salary by the percent specified.
  • HourlyCompensationModel - For Employees who are paid by the hour and receive overtime pay for all hours worked in excess of 40 hours per week. This class should contain instance variables of wage and hours and should implement method earnings() based on the number of hours worked. For any hours worked over 40, they should be paid at an hourly wage of 1 and a half times their wage. So if their normal wage is $10 per hour normally, they would get $15 per hour for overtime. It should also implement the method raise(double percent) by increasing the wage by the percent specified.
  • CommissionCompensationModel - This class is the same as in Asssignment 2 except that this class is now a subclass of CompensationModel. It should also implement the method raise(double percent) by increasing the commission rate by the percent specified.
  • BasePlusCommissionCompensationModel - This class is the same as in Assignment 2, a subclass of CommissionCompensationModel . It should also implement the method raise(double percent) by increasing the base salary by the percent specified.

Each of these classes will also have a toString() method to display their compensation information as illustrated in the sample output below.

Modify the Employee class of Assignment 2 to have an instance variable of type CompensationModel instead of CommissionCompensationModel, Make any other necessary changes in the Employee class because of this. Also add the raise (double percent) method to the Employee class which simply calls the raise method of the CompensationModel.

Use the following code in your main function to test your classes, just copy and paste it into your main method:

        // Create the four employees with their compensation models.
       
        CommissionCompensationModel commissionModel = new CommissionCompensationModel(2000.00, 0.04);
        BasePlusCommissionCompensationModel basePlusCommissionModel = new BasePlusCommissionCompensationModel(2000.00, 0.05, 600.00);
        SalariedCompensationModel salariedCompensationModel = new SalariedCompensationModel(2500.00);
        HourlyCompensationModel hourlyCommissionModel = new HourlyCompensationModel(10.00, 35.0);
       
        Employee employee1 = new Employee("John", "Smith", "111-11-1111", commissionModel);
        Employee employee2 = new Employee("Sue", "Jones", "222-22-2222", basePlusCommissionModel);
        Employee employee3 = new Employee("Jim", "Williams", "333-33-3333", salariedCompensationModel);
        Employee employee4 = new Employee("Nancy", "Johnson", "444-44-4444", hourlyCommissionModel);
       
        // Print the information about the four employees.
        System.out.println("The employee information initially.");
        System.out.printf("%s%n%s%n%s%n%s%n", employee1, employee2, employee3, employee4);
        System.out.printf("%s%s%s%s%s%8.2f%n%n", "Earnings for ", employee1.getFirstName(), " ", employee1.getLastName(), ": ", employee1.earnings());
       
        // Change the compensation model for the four employees.
       
        CommissionCompensationModel commissionModelNew = new CommissionCompensationModel(5000.00, 0.04);
        BasePlusCommissionCompensationModel basePlusCommissionModelNew = new BasePlusCommissionCompensationModel(4000.00, 0.05, 800.00);
        SalariedCompensationModel salariedCompensationModelNew = new SalariedCompensationModel(3500.00);
        HourlyCompensationModel hourlyCommissionModeNewl = new HourlyCompensationModel(10.00, 50);
       
        // Set the new compensation models for the employees.
        employee1.setCompensation(basePlusCommissionModelNew);
        employee2.setCompensation(commissionModelNew);
        employee3.setCompensation(hourlyCommissionModeNewl);
        employee4.setCompensation(salariedCompensationModelNew);
       
        // Print out the new information for the four employees.
        System.out.println("The employee information after changing compensation models.");
        System.out.printf("%s%n%s%n%s%n%s%n", employee1, employee2, employee3, employee4);
       
        // Declare an array of employees and assign the four employees to it.
        Employee[] employees = new Employee[4];
        employees[0] = employee1;
        employees[1] = employee2;
        employees[2] = employee3;
        employees[3] = employee4;
    
        // Loop thru the array giving each employee a 2% raise polymorphically;
        for (Employee employee : employees)
        {
            employee.raise(.02);
        }
       
        // Print out their new earnings.
        System.out.println("The employee information after raises of 2 percent.");
        System.out.printf("%s%n%s%n%s%n%s%n", employee1, employee2, employee3, employee4);
   

The output from your program should look like the following (there will be additional blank lines in the output which canvas removes for me, unwanted, in this display):

run:
The employee information initially.
John Smith
Social Security Number: 111-11-1111
Commission Compensation with:
Gross Sales of: 2000.00
Commission Rate of: 0.04
Earnings:    80.00

Sue Jones
Social Security Number: 222-22-2222
Base Plus Commission Compensation with:
Gross Sales of: 2000.00
Commission Rate of: 0.05
Base Salary of:   600.00
Earnings:   700.00

Jim Williams
Social Security Number: 333-33-3333
Salaried Compensation with:
Weekly Salary of: 2500.00
Earnings: 2500.00

Nancy Johnson
Social Security Number: 444-44-4444
Hourly Compensation with:
Wage of:    10.00
Hours Worked of:35.00
Earnings:   350.00

Earnings for John Smith:    80.00

The employee information after changing compensation models.
John Smith
Social Security Number: 111-11-1111
Base Plus Commission Compensation with:
Gross Sales of: 4000.00
Commission Rate of: 0.05
Base Salary of:   800.00
Earnings: 1000.00

Sue Jones
Social Security Number: 222-22-2222
Commission Compensation with:
Gross Sales of: 5000.00
Commission Rate of: 0.04
Earnings:   200.00

Jim Williams
Social Security Number: 333-33-3333
Hourly Compensation with:
Wage of:    10.00
Hours Worked of:50.00
Earnings:   550.00

Nancy Johnson
Social Security Number: 444-44-4444
Salaried Compensation with:
Weekly Salary of: 3500.00
Earnings: 3500.00

The employee information after raises of 2 percent.
John Smith
Social Security Number: 111-11-1111
Base Plus Commission Compensation with:
Gross Sales of: 4000.00
Commission Rate of: 0.05
Base Salary of:   816.00
Earnings: 1016.00

Sue Jones
Social Security Number: 222-22-2222
Commission Compensation with:
Gross Sales of: 5000.00
Commission Rate of: 0.04
Earnings:   204.00

Jim Williams
Social Security Number: 333-33-3333
Hourly Compensation with:
Wage of:    10.20
Hours Worked of:50.00
Earnings:   561.00

Nancy Johnson
Social Security Number: 444-44-4444
Salaried Compensation with:
Weekly Salary of: 3570.00
Earnings: 3570.00

PreviousNext

In: Computer Science

what does this code do? int encrypt(int character, int shift) { if(character >= 'a' && character...

what does this code do?

int encrypt(int character, int shift) {
if(character >= 'a' && character <= 'z') {
return 'a' + (((character-'a'+shift) % 26) + 26) % 26 ;
} else if (character >= 'A' && character <= 'Z') {
return 'A' + (((character-'A'+shift) % 26) +26) % 26;
} else {
return character;
}
}

int main(int argc, char *argv[]) {
int ch;
int key = 3;
if(argc == 2) {
key = atoi(argv[1]);
}
while((ch = getchar()) != EOF) {
printf("%c", encrypt(ch, key));
}
return 0;
}

how does this work as I am confused about the % used.

In: Computer Science

IN PYTHON Your task this week is to use loops to both validate user input as...

IN PYTHON

Your task this week is to use loops to both validate user input as well as automate a test suite for your lab solution from last week.

Your program will prompt the user for the cost of their groceries.

Then you are to calculate the value of the coupon to be awarded based on the amount of the grocery bill. Use the table below to determine coupon amounts.

Money Spent   Coupon Percentage
Less than $10   0%
From $10 to less than $60 8%
From $60 to less than $150 10%
From $150 to less than $210    12%
From $210 or more 14%

Display an appropriate result message to the user including both the coupon percentage awarded and the dollar amount of their discount coupon.

Last week we trusted the user to provide valid input. This week you will ensure that valid user input is obtained by implementing an input validation loop.

Last week the test requirement was to prove that your solutions worked for one of the coupon tiers. This week your solution will test each of the possible coupon tiers by using a loop to iterate through all the possible test cases in one program execution.

Testing Requirements

Input Error Checking: Validate user input. Test for both non-numeric, and negative values. If the user does not supply valid input, use a loop to keep the user from advancing until a correct value (a number >= 0) is entered. This technique of using a loop to repeat prompting until correct input is entered is sometimes referred to as 'pigeonholing' the user until he/she gets it right.

Testing Requirements:  Using looping control structures, run your program through an entire suite of candidate test data. Include the following test cases: apple, -1, 0, 10, 70, 160, 222. Note:  Your program needs to execute all 7 test cases in one one of your program.

Here are some other requirements (remaining from lab 3's spec):

  1. Create constants versus using literals in your source code.
  2. Use a float to represent both the shopper’s grocery bill as well as the coupon amount.
  3. Format the discount coupon amount to 2 decimal places (Example: $19.20).

Here are some requirements specific to this expanded lab 4 spec:

4. Run a test suite that validates user input. Do not allow the user to advance until a valid data entry is provided.

5. Your submitted test run should include all the specified test cases: apple, -1, 0, 10, 70, 160, 222. All test cases are to be executed in one program run by using a loop structure.

Here is an example run:

'''
Please enter the cost of your groceries: apple
Enter cost >= 0: -1
Enter cost >= 0: 0
You win a discount coupon of $0.00. (0% of your purchase)
Please enter the cost of your groceries: 10
You win a discount coupon of $0.80. (8% of your purchase)
Please enter the cost of your groceries: 70
You win a discount coupon of $7.00. (10% of your purchase)
Please enter the cost of your groceries: 160
You win a discount coupon of $19.20. (12% of your purchase)
Please enter the cost of your groceries: 222
You win a discount coupon of $31.08. (14% of your purchase)

'''

Tips and requirements:

  1. Create constants versus using literals in your source code.
  2. Use a float to represent both the shopper’s grocery bill as well as the coupon amount.
  3. Format the discount coupon amount to 2 decimal places (Example: $19.20).
  4. Show your program run for all of the test cases: -1, apple, 0, 10, 70, 160, 222. Note: Your program needs to work for all 7 test cases. Your program test run only needs to demonstrate all of the test cases in one program run.

In: Computer Science

Book SerialNum : String - Name: String – Author : String PublishYear: int - Edition:int Status...

Book

SerialNum : String -

Name: String –

  • Author : String

PublishYear: int -

  • Edition:int
  • Status : boolean

+ Book()

Book(String, String, String, int , int)+

+ setName(String) : void

+ setSerialNum(String) : void

+ setAuthor(String) : void

+ setEdition(int) : void

+ setYear(int) : void

+ getName():String

+ getAuthor():String

+ getYear(): int

+ getSerialNum(): String

+ getEdition():int

+ setAvailable() : void

+ setUnavailable(): void

checkAvailability(): boolean

-----------------------------------------------------------------------------------

Library

Name : String

Address: String

Static NUMBEROFBOOKS: int

BooksAtLibrray : ArrayList

LibraryIssues: TreeMap

Library()

Library(String, String)

addBook(Book): void

removeBook(Book) : Boolean

searchBookByName(Book) : Boolean

searchBookBySerialNumber(Book) : Boolean

checkBookAvailablity(Book): Boolean

createLibraryIssue(LibrrayIssue):Boolean

addLibraryIssue(LibraryIssue)

removeLibrrayIssue(LibrrayIssue):Boolean

searchLibrrayIssueByStuent(Student): List

searchLibraryIssuebyID(String IssueID):LibrrayIssue

searchLibraryIssueByBook(Book): LibraryIssue

--------------------------------------------------------------------------------------------------------------

Student

id : String

Name: String

Age : int

Student()

Student(String, String, int)

setName (String):void

SetAge(int):void

setId(String):void

getID():String

getName():String

getAge():int

---------------------------------------------------------------------------------------------------

LibraryIsuue

IssueID : String

borrower : Student

borrowedBook : Book

LibraryIssue()

LibraryIssue(String, Student , Book)

setIssueId(String):void

setBorrower(Student):void

setBorrowedBook(Book):void

getIssueID():String

getBorrowed():Student

getBorrowedBook():Book

----------------------------------------------------------------------------------------------------------

Librray

Main()

-----------------------------------------------------------------------------------------------------------------------------------------

Use the attached UML diagrams to build up your project classes

Make sure to put view for your project by Entering true data

You will need to add 5 books and 5 students and at least 3 LibraryIssues

LibraryIssues keeps track of the borrowed book

The librray uses all classes as mentioned in the UML diagram

You will need to check if book is available before borrowing it.

searchLibrrayIssueByStuent(Student): List

This method returns all book if borrowed by single student, as a student could borrow more than one book

Static NUMBEROFBOOKS: int

Each time you add a book the static variable is increased  and Each time a book is removed so the static variable is decreased.

createLibraryIssue(LibraryIssue) : boolean

changed the Boolean variable status in book element to false and return false if book is not available

removeLibrrayIssue(LibraryIssue):Boolean

changed the Boolean variable status in book element to true and return false if book is available

Note

LibrrayIssue and Book in the class Library should be List or map

Do not use array as the size is not fixed

In: Computer Science

When a customer or a powerful manager pushes a bad idea on a Project Manager (PM),...

When a customer or a powerful manager pushes a bad idea on a Project Manager (PM), a PM must learn "intelligent disobedience," that is, the ability to say "no" to demands that might put the project and, thus the company, in harm's way. If you were a PM facing a bad idea from a customer or a powerful manager, how would you say "no"?

In: Computer Science

Assembly Language homework assignment has 2 parts which require 2 separate programs. Submit both source code...

Assembly Language
homework assignment has 2 parts which require 2 separate programs. Submit both source
code files .
Question 1 of 2. Integer arithmetic: [20 marks] Write an assembly language program that performs the following arithmetic operation on 4 integer numbers.
?????? = ((2∗?)+? )/(?+?)
1. Reserve memory for 4 integers and initialize them to numbers of your choice.
2. Reserve 4 bytes of memory for a single integer to store the result of the operation in a
READWRITE section of memory.
3. Load the numbers from memory and perform the above operation.
4. Store the result back into of memory.
For this part of the assignment, we shall work with 4 integers namely A, B, C, D. We can declare them as 4 separate variables or a single array with 4 numbers. We need to MULtiply the number A with 2 and then ADD the result to B. We also need to ADD C and D together to get the divisor. Following this we need to perform Signed DIVision of the two intermediate results in order to obtain the final result. This is an integer arithmetic operation, so division would not give you a floating-point result. All remainders are ignored. Division with a number higher than the dividend would result in 0. This follows traditional integer division as in C++.
Make sure your code works for any input number, not just the test cases. Your code will be tested on other test cases not listed here.
Please properly comment your code before submission.

In: Computer Science

Using Java Create two exception classes to capture the improper entering of coin names and their...

Using Java

Create two exception classes to capture the improper entering of coin names and their corresponding values. Name one class CoinNameException and the other CoinValueException

Design and write a program that asks a young child to input a set of coin names and their corresponding values (in cents) in their piggybank. The program should work in a loop:

  1. First, the program should prompt the child to enter the name of a coin (penny, nickel, dime, quarter, or half-dollar).
    • If an improper name for a coin is entered, then catch a CoinNameException exception, print an error message, and give the child a second chance to reenter it.
    • After two chances, terminate the program.
  2. Once a valid coin name has been entered in step #1 above, the child must then enter the corresponding value of that coin in cents (1, 5, 10, 25, or 50).
    • Use either the parseInt() or the nextInt() method to get the value of the coin.
      • Hint: What exceptions can these methods throw?
    • If the child enters the wrong value for the coin, then catch a CoinValueException exception, print an error message, and give the child a second chance to reenter the value of the coin.
    • After two chances, terminate the program.
  3. If a valid coin and its corresponding value are entered, add that coin to the child’s piggybank total and go back to step #1
  4. Other than entering an invalid coin name or value twice, provide a nicer and simpler way for the child to exit the loop above (steps 1 – 3)
  5. When the child is finished entering coins (or the program terminates), display a nicely-formatted report showing the name, value, and quantity of each coin in the child’s piggybank, along with the total value of all coins.

All exception classes should have at least two constructors:

  • one which takes no arguments and provides a default Exception message
  • another which takes a String as an argument and sets the contents of the String as the Exception message

In: Computer Science

What is the difference between “System Of Systems” and “System Of Sub-systems”? Give one example of...

What is the difference between “System Of Systems” and “System Of Sub-systems”? Give one example of each.

In: Computer Science

Using Java A stack is a type of data collection on which things can be “pushed”...

Using Java

A stack is a type of data collection on which things can be “pushed” and “popped”. For example, a stack of plates can have a plate added (or “pushed”) onto the stack, and a plate removed (or “popped”) from the stack. Plates are pushed onto or popped off of the stack one at a time. The last plate pushed onto the stack is the first plate popped off of the stack. This type of structure is known as “LIFO” – last in, first out.

In this project, you will create a stack that will hold objects of type Person. The stack itself will be in a class named PersonStack.

When manipulating the stack, three types (or classes) of exceptions can be thrown. Each Exception class will contain two constructors, one which provides a default message for the exception, and one which takes a String as an argument and sets the exception message to that String.

The three Exception classes in this project are:

  1. StackFullException – thrown when trying to add (or “push”) an object onto the stack which already has reached its maximum size. The default exception message is

"PersonStack is full – object not added."

  1. StackEmptyException – thrown when trying to remove (or “pop”) an object from the stack when the stack is empty. The default exception message is

"PersonStack is empty – no object to return."

  1. IllegalObjectTypeException – thrown when trying to add an object to the stack that is not an instance of the correct type of object which the stack can hold. (In this project, the stack holds objects of type Person.) The default exception message is

"Object is not a Person – object not pushed."

Each class above extends Exception, so it is “checked”, and must appear inside a try-catch statement.

Next, you should define a class called PersonStack, which will implement the stack containing an array of Person objects. (Use the Person and Date classes provided on Canvas below.)

The details of this project:

  • The stack is implemented using an array with a capacity of 5 Person objects.  Initially it will be empty (contain no objects)
  • An int variable is used to point to the “next available stack position” in the array. Initialize this variable to 0, meaning that the stack is empty.
  • The class will provide a method named push(), which will take one argument, an object of type Object.
    • If the object is null, or if the object is not an instance of the Person class, then this method will throw an exception of type IllegalObjectTypeException, but the push method will not catch the exception.
    • If the stack is full, then this method will throw an exception of type StackFullException, but will not catch it.
    • Otherwise, the method will typecast the object to a Person, place the object on top of the stack (the element in the array referenced by the “next available stack position” variable), and increment that variable.
  • The class will provide a method named pop():
    • If the stack is empty, this method will throw an exception of type StackEmptyException, but will not catch it
    • Otherwise, the method will decrement the variable referencing the “next available stack position”, remove the Person object currently occupying that position from the stack (array), and return the Person object that was just removed from the stack.
  • The class will provide a method named toString(), which lists all of the Person objects currently residing on the stack.
  • You do not need to include an equals method for the PersonStack class

Finally, you will need to write a main “tester” program. (Please put this method in its own class, not with PersonStack.) This program will:

  • Instantiate an object of the PersonStack class – aka the “stack”.
  • Inside a “try” block:
    1. Instantiate and “push” 5 different Person objects onto the stack.  
    2. Print the contents of the stack (use the stack’s toString method).
    3. Attempt to “push” a 6thPerson object onto a stack, which should throw a StackFullException.
  • Inside a second “try” block
    1. “Pop” five Person objects from the stack. As each is “popped”, print a message showing which Person object was returned.
    2. The stack should now be empty. Try to “pop” a 6th object from the stack, which should throw a StackEmptyException.
  • In a third “try” block:
    1. Instantiate an object of any type other than Person. (For example, you could use a Date or a String)
    2. Try to “push” this object onto the stack. This should throw an IllegalObjectTypeException
  • After each “try” block above, you will need to add “catch” blocks to handle the types of exceptions which can be thrown by methods inside the “try” block, because those methods do not handle the exceptions themselves.
    1. The “push” method can throw a StackFullException and an IllegalObjectTypeException.
    2. The “pop” method can throw a StackEmptyException.

In each “catch” block, print the exception message, but do not stop.

Please do not change the Person or Date classes.  

A sample dialog might look like:

  Just added five people onto the stack
  Here are the contents of the stack: 
     Name: Harry Potter  born: July 31, 1997
     Name: Beyoncé  born: September 4, 1981
     Name: James T. Kirk  born: March 22, 2233
     Name: Tom Brady  born: June 1, 1989
     Name: Oprah Winfrey  born: March 25, 1975
  Trying to push one more onto the stack:
  PersonStack is full - object not added

  Popping the contents of the stack plus one.
     Popped: Name: Oprah Winfrey  born: March 25, 1975  
     Popped: Name: Tom Brady  born: June 1, 1989
     Popped: Name: James T. Kirk  born: March 22, 2233
     Popped: Name: Beyoncé  born: September 4, 1981
     Popped: Name: Harry Potter  born: July 31, 1997
  PersonStack is empty - no object to return
 
  Trying to add an Object object to the stack. 
  Object not a Person - object not pushed

In: Computer Science

Create a post describing something in your life that has a bad user interface. It does...

Create a post describing something in your life that has a bad user interface. It does not have to be computer related, though a bad computer interface would certainly be on topic. In your post include the following:

  1. An image of the interface. You can take a picture of it, or a screen capture, and then embed the image within your discussion forum post, rather than uploading it as an attachment. If not, see if you can find an image of your interface on the web to use.*
  2. Describe what about the interface makes it so bad.
  3. Make three design recommendations for improving the interface.

In: Computer Science

JAVA FILE PROGRAM Write a contacts database program that presents the user with a menu that...

JAVA FILE PROGRAM

Write a contacts database program that presents the user with a menu that allows the user to select between the following options:

  • Save a contact.
  • Search for a contact.
  • Print all contacts out to the screen.
  • Quit

If the user selects the first option, the user is prompted to enter a person's name and phone number which will get saved at the end of a file named contacts.txt.
If the user selects the second option, the program prompts the user asking for the name of the contact. It then searches the contacts.txt for a matching name. If found, it displays the phone number on the screen. If not found, it will display an appropriate error message.
If the user selects the third option, the program displays all contacts stored in contacts.txt in a neat table.
The program is menu driven and will repeat presenting the menu and processing choices until the user selects the fourth option to quit.
If the user selects an invalid option, an appropriate error message should be displayed.
If the user selects to print all contacts to the screen with no stored contacts, an appropriate error message should be displayed.

You may use message dialogs or make it a purely console-based application

In: Computer Science

List any 5 Unix commands with their brief description.

List any 5 Unix commands with their brief description.

In: Computer Science

You will extend last week's workshop activity by adding a Player class. Each player has a...

You will extend last week's workshop activity by adding a Player class. Each player has a number of Pokemons, and the player can select one of his or her Pokemon to play against another player's Pokenmon. The player who lost the battle lost his or her Pokemon to the other player.

You will be working with three.java files in this zyLab.

  • Pokemon.java - Class definition (completed)
  • Player.java - Class definition
  • PokemonField.java - Contains main() method
  1. Complete the Player class with the following specifications:

    (1) add the following three private fields

    • String name
    • int level
    • ArrayList pokemons

    (2) add a constructor, which takes one parameter to initialize the name field. The level is initialized as 0. The constructor also creates the ArrayList.

    (3) add each of the following public member methods

    • getName()
    • getLevel()
    • getPokemons()
    • setLevel(int level)
    • addPokemon(Pokemon p)
    • removePokemon(Pokemon p)
    • printStat()
  2. Complete the PokemonField.java

PokemonField.java

import java.util.Random;
import java.util.Scanner;

public class PokemonField {
  
public static void main(String[] args) {

Player player1 = new Player("dragonslayer");
Player player2 = new Player("voldemort");
Random random = new Random();
  
initialize(player1, player2);
player1.printStat();
player2.printStat();
  
play(random, player1, player2);
  
System.out.println("Game over");
  
player1.printStat();
player2.printStat();
}
  
public static boolean fight(Random random, Pokemon p1, Pokemon p2){
double prob = (double)p1.getAttackPoints() / (p1.getAttackPoints() + p2.getAttackPoints());
while(p1.getHitPoints() > 0 && p2.getHitPoints() > 0) {
if(random.nextDouble() < prob) {
p2.setHitPoints(Math.max(p2.getHitPoints()- p1.getAttackPoints(), 0));
}
else{
p1.setHitPoints(Math.max(p1.getHitPoints() - p2.getAttackPoints(), 0));
}
}
  
if(p1.getHitPoints() > 0){
System.out.println(p1.getName() + " won!");
return true;
}
else {
System.out.println(p2.getName() + " won!");
return false;
}
}
  
public static void initialize(Player player1, Player player2) {
String[] pokemonNames1 = {"Butterfree", "Ivysaur", "Pikachu", "Squirtle"};
int[] pokemonMaxHps1 = {10, 15, 20, 30};
int[] pokemonAps1 = {1, 2, 2, 3};
String[] pokemonNames2= {"Jigglypuff","Oddish","Gloom","Psyduck","Machop"};
int[] pokemonMaxHps2 = {12, 18, 25, 27, 32};
int[] pokemonAps2 = {1, 1, 2, 2, 3};
  
for(int i = 0; i < pokemonNames1.length; i++) {
/*FIX(1) create a Pokemon object with the following three arguments:pokemonNames1[i], pokemonMaxHps1[i], pokemonAps1[i]
Add the Pokemon object to the Pokemon array list in player1
Increment player1's level by 1*/

}
  
for(int i = 0; i < pokemonNames2.length; i++) {
/*FIX(2) create a Pokemon object with the following three arguments:pokemonNames2[i], pokemonMaxHps2[i], pokemonAps2[i]
Add the Pokemon object to the Pokemon array list in player2
Increment player2's level by 1*/
}
  
}
  
public static void play(Random random, Player player1, Player player2) {
Pokemon p1, p2;
int index1, index2;
Scanner scnr = new Scanner(System.in);
boolean result;
  
System.out.println("Let's play!");
System.out.println(player1.getName() + " choose a pokemon to fight\nenter 1 to " + player1.getPokemons().size() + " or -1 to stop");
index1 = scnr.nextInt();
System.out.println(player2.getName() + " choose a pokemon to fight\nenter 1 to " + player2.getPokemons().size() + " or -1 to stop");
index2 = scnr.nextInt();
  
while(index1 != -1 && index2 != -1) {
p1 = player1.getPokemons().get(index1-1);
p2 = player2.getPokemons().get(index2-1);
  
result = fight(random, p1, p2);
if(result) {
/*FIXME(3) p1 won, reset p2, remove p2 from player2, and add p2 to player 1, increment player1's level by 1*/
  
}
else {
/*FIXME(4) p2 won, reset p1, remove p1 from player1, and add p1 to player 2, increment player2's level by 1*/
}
  
System.out.println(player1.getName() + " choose a pokemon to fight\nenter 1 to " + player1.getPokemons().size() + " or -1 to stop");
index1 = scnr.nextInt();
System.out.println(player2.getName() + " choose a pokemon to fight\nenter 1 to " + player2.getPokemons().size() + " or -1 to stop");
index2 = scnr.nextInt();
}
}
}

Player.java

import java.util.ArrayList;
public class Player {
/*FIXME(1) Add three fields: name, level, pokemons*/
  
  
/*FIXME(2) Add a constructor, which takes one parameter: String n.
Initialize name to n, level to 0, and create an ArrayList for pokemons*/


/*FIXME (3) Define the accessor for name*/

  
/*FIXME (4) Define the accessor for level*/


/*FIXME (5) Define the accessor for pokemons*/
  
  
/*FIXME (6) Define the mutator for level*/
  


/*FIXME(7) Complete this method by adding p into the Pokemon ArrayList*/
public void addPokemon(Pokemon p){

}

/*FIXME(8) Complete this method by removing p from the Pokemon ArrayList*/
public void removePokemon(Pokemon p){

}
  
public void printStat(){
System.out.println("\nPlayer: " + name + " at level " + level + ", has " + pokemons.size() + " pokemons");
/*FIXME(9) Complete this method by printing the stat of each pokemon in the Pokemon ArrayList.
Each pokemon's stat is printed in an individual line. Hint: loop through the ArrayList and call the printStat method of Pokemon class*/

}   
}

Pokemon.java

public class Pokemon {
private String name;
private int maxHp;
private int hitPoints;
private int attackPoints;
  
public Pokemon(String name, int maxHp, int ap) {
this.name = name;
this.maxHp = maxHp;
hitPoints = maxHp;
attackPoints = ap;
}
  
public String getName(){
return name;
}
  
public int getHitPoints() {
return hitPoints;
}
  
public int getAttackPoints() {
return attackPoints;
}
  
public void setHitPoints(int hp) {
hitPoints = hp;
}

public void setAttackPoints(int ap) {
attackPoints = ap;
}

public void reset() {
hitPoints = maxHp;
}
public void printStat() {
System.out.println(name + " has " + hitPoints + " hit points and " + attackPoints + " attack points");
}
}

  
  
/*FIXME(2) Add a constructor, which takes one parameter: String n.
Initialize name to n, level to 0, and create an ArrayList for pokemons*/


/*FIXME (3) Define the accessor for name*/

  
/*FIXME (4) Define the accessor for level*/


/*FIXME (5) Define the accessor for pokemons*/
  
  
/*FIXME (6) Define the mutator for level*/
  


/*FIXME(7) Complete this method by adding p into the Pokemon ArrayList*/
public void addPokemon(Pokemon p){

}

/*FIXME(8) Complete this method by removing p from the Pokemon ArrayList*/
public void removePokemon(Pokemon p){

}
  
public void printStat(){
System.out.println("\nPlayer: " + name + " at level " + level + ", has " + pokemons.size() + " pokemons");
/*FIXME(9) Complete this method by printing the stat of each pokemon in the Pokemon ArrayList.
Each pokemon's stat is printed in an individual line. Hint: loop through the ArrayList and call the printStat method of Pokemon class*/

}   
}

In: Computer Science