Chapter 4/Debugging 4-1.png __MACOSX/Chapter 4/._Debugging 4-1.png Chapter 4/Debugging 4-3b.png __MACOSX/Chapter 4/._Debugging 4-3b.png Chapter 4/Chapter 4 Excercises.pdf Print Previerv I of 8...

1 answer below »
Programming Java


Chapter 4/Debugging 4-1.png __MACOSX/Chapter 4/._Debugging 4-1.png Chapter 4/Debugging 4-3b.png __MACOSX/Chapter 4/._Debugging 4-3b.png Chapter 4/Chapter 4 Excercises.pdf Print Previerv I of 8 https://ng.cengage.com/static/nbreader/ui/apps/nbrcader/pri nt_p.. Chapter 4: More Obiect Concepts: 4-1Od Exercises Book Tifle: Java* Programming Printed By : WeMy Pefiick (werdy. petrick@ email. saintleo.edu) @ 2019 Cengage, Cengage Leaming, lnc. Chapter Review +10d Exercises Programming Exercises 1. Create a dass named FormletterWri ter that indudes two overloaded methods named d i spl ay Sa1 utat i on ( ) . The first method takes one S t r i ng parameter that represents a customer's last name, and it displays the salu&ation Dear Mr. or Ms. followed bythe last name. The second method acoepts two Stri ng parameters that represent a first and last name, and it displays the greeting Dearfollowed bythe first name, a spa@, and fte last name. After each salutation, display the rest of a short business letter: Thank you for your reent order. Write a mai n ( ) method that tests each overloaded meftod. Save the file as Forml-etterWriter.java. 2- Creale a class named Bi lli ng that indudes three overloaded computeBi 11O methods for a photo book store. . When computeBi 11 ( ) receives a single parameter, it represents the price of one photo book ordered. Add 8% tax, and return the total due- . When computeBi 11O receives two parameters, they represent the price of a photo book and the quantity ordered. Multiply the two values, a&$o/" tan, and retum the total due. . When computeBi 11O receives three parameters, they represent the price of a photo book, the quantity ordered, and a coupon value. Multiply the quantity and price, reduce the result by the coupon value, and then add 8% tax and retum the total due. Write a ma i n ( ) method that tests all three overloaded methods- Save the application as Billing.iava. 4l3O/19,7:31 PM Print Preview 3. https://ng cengage.comlstatic/nbreader/ui/apps/nbreader/print_p... a. Create a Fi tnessTracker dass that indudes data fields for a frhess activity, the number of minutes spent participating, and the date. The dass includes meffiods to get each feld. ln additbn, create a default constructor that automatically sets the activity lo running, the minutes to 0, and the date to January 1 of the cunent year. Save the file as Fthess'Tracker,java. Create an application that demonstrates each method works conectly, and save it as TestFitnessTrac-ker.iava. b. Create an additionaloverloaded consffiuctorforthe Fi tnessTracker dass you created in Exercise 3a- This consffuctor receives paraneters for each of the data fields and assigns them appropriately. Add any needed staternents to fte TestFi tnessTracker application to ensure that the overloaded constructor works conectly, save it, and then test it. c. Modify the Fi tnessTracker class so that the default constructor calls the three-parameter constuctor. Save the dass as Fihess'Trackerllava. Create an application to test the new version of the class, and name it TestFrtnesSTracker2.iava. a. Create a dass named BloodData that indudes fields that hold a blood t)rpe (tre four blood types are O, A, B, aN AB) aN an Rh factor (the factors are + and -). Create a default @nstructor that sets the fields to Oafi+, and an overloaded @nsfiuctorthat requirm values for both fields. lnclude gpt and set methods for eacfi field. Save this file as BloodDah java. Create an application named TestBloodData that dernonsfrates each metpd works conec{y. Save the application as T6tBlood[lata.java. b. Greate a class named Patient that includes an lD number, age, and BloodData. Provide a default oonstructor that sets the lD number to 0, the age to 0, and the BloodData values to O and +. Create an overloaded onsfructorthat provides values for each field. Also provide get methods for each field. Save the file as PaUentjava. Create an application that demonstates that each method works onecty, and save it as TestPatienliava- a. Create a class to hold data about a high school sports team. The Team class holds data fields for high school name (such as Roosevelt High), sport (such as Girls'BaskebalD, and team name (such as Dolphinsl- lnclude a constructor that takes parameters for each field, and include 4. 2 of8 5. 4l3ol19,'7:3lYM Print Prer ies 3 of8 6. https://ng -cengage.comlstalic/nbreader/ui/apps/nbreader/pri nt_p... get methods that return the values of the fields. Also include a publ i c f i naI stati c Stri ng named H0TT0 and initialize it to Sportsmanship!. Write an application named TestTeam to instantiate three Team objects with different values, and then display all the data, including the motto, for each object. Save both the Team.java and TestTeam.java files. b. Create a class named Game. lrxCude two Team fields that hold data about the teams participating in the game. Also include a field for game time (for example, 7 PM.lrdude a onstructor that takes parameters for two Team objects and a time. Write an application named TestGame to instantiate a Game obiect, then pass the Game to a method that displays the details about the Game. a. Create a class named Ci rcle with fields named radi us, di ameter, and area. lnclude a mnstructor that sets the radius to 1 and calculates the other two values. Also include methods named setRadi us ( ) and getRadi us ( ). The setRadi us ( ) method not only sets the radius, but it also calculates the other two values- (The diameter of a circle is twice the radius, and the area of a circle is pi multiplied by the square of the radius. Use the ltlath class PI constant for this calculation.) Save the class as Circle.java. b. Create a class named TestCi rcle whose mai n O rnethod declares severai Ci rcle objects. Using the setRadi us ( ) method, assign one Ci rcle a smali radius value, and assign another a larger radius value. Do not assign a value to the radius of the third circle; instead, retain the value assigned at construction. Display all the values for all the C i r c i e objects. Save the application as TestCircle.java. 7. Write a Java application that uses the Hath class to determine the answers for each of the following: a. The square root of 37 b. The sine and cosine of 300 c. The value of the floor, ceiling, and round of 22-8 d. The larger and the smaller of the character'D'and the integer 71 1l30ll9-7:31 PM I)rint Prer ieu -tof8 https://ng.cengage.com/static/nbreader/ui/appvnbreader/pri nt p..- e. A random number between 0 and 20 (Hint The randomO method returns a value between 0 and 1;you want a number that is 20 times larger.) Save the application as MathTest.iava. 8. Write a program that declares two LocalDate obiects and assign values that represent January 31 and December 31 in the current year. Display output that demonstrates the dates displayed when one, two, and three rnonths are added to each of the obiects. Save the applicatbn as Testilonth Hand I i ng. java. 9. Write an application that oomputes and displays the day on whicfr you become (or became) 10,000 days old. Save ttre application as TenThousand DaysOld.iava. 10. The LocalDate class includes an instance method named length0f t{onth ( ) that retums the number of days in the rnonth. Write an application that uses methods in the LocalDate class to calculate how many dalts are left until the first day of next month. Display the result, induding the name of the next month. Save the file as DaysTilNextlrlonth.iava. 11. Create a class named Person that holds the following fields: two Str i ng obiects for the person's first and last name and a LocalDate obiect for the person's birthdate. Create a class named Couple that contains two Person objects. Create a class named Weddi ng for a wedding planner that includes the date of the wedding, the names of the Couple being manied, ard a Stri ng for the location. Provide constructors for each class that accept parameters for each field, and provide get methods for eacfi field. Then write a program that creates two Weddi ng objecb and in tum passes each to a method that displap allthe details. Save the ftles as Person.iava, Gouple.java, Wedding .iava, and TestWedding.iava. Debugging Exercises 1. Each of the following files in the Chapte(X folder of your downloadable student files has syntax and/or logic enors. ln each case, determine the 1l30l19.7:31PM Print Pretieu. 5 of8 https://ng.cen gage.com/static/nbreader/ui/apps/nbreader/pri nt_p. problem and fix the program. After ),ou corect the enors, save eaclr file using the same filename preceded with frx. For example, save DebugFourl.iava as FixllebugFourl.iava. a. DebugFourl.java b. DebugFour2.iava c. DebugFour3.java and DebugBox.java d. DebugFour4.iava When you change a filename, remember to change every instance of the class name within the file so that it matches the new filename. ln Java, the filename and class name must always match. "$'-4f{t€ Game Zone 1. Dice are used in many games. One die can be thrown to randomly shovr a value from 1 through 6. Design a Di e class that can hold an integer data field for a value (frorn 1 to 6). lnclude a constructor that randomly assigns a value to a die object. contains information about generating random numbers. To fully understand the process, you must learn more about Java classes and methods. However, for now, you can copy the following statement to generate a random number between 1 and 6 and assign it to a variable. Uslng this statement assumes you have assigned appropriate values to the static constants. rarndomValue 5 ((;nt,t(n"ath.r;rndonr() '' 100) '', ttICltEST DIE VALUE + L0},EST i)IF. VALtJFi: Also include a method in the class to retum a die's value. Save the class as Die.java. Write an application that randomly throws" two dice and displays their values. After you read the chapter "Making Decisions," you will be able to have the game determine the higher die. For now, just observe how the values change as you execute the program multiple times. Save the application as TwoDice.java. $3A119.7:31 PM Print Prer ieu 6 of8 https:1/ng.cengage.com/static/nbreader/ui/apps/nbreaderlpri nt_p... 2. Using the Di e class, write an application that randomly throws" five dice for the computer and five dice for the player. Display the values and then, by observing the results, decide who wins based on the following hierarchy of Di e values. (The computer will not decide the winner; the
Answered Same DayMay 02, 2021

Answer To: Chapter 4/Debugging 4-1.png __MACOSX/Chapter 4/._Debugging 4-1.png Chapter 4/Debugging 4-3b.png...

Aditi answered on May 14 2021
142 Votes
Solution/chapter3/Debugging/FixDebugThree1.java
Solution/chapter3/Debugging/FixDebugThree1.java
// This class calculates a waitperson's tip as 15% of the bill
public class FixDebugThree1
{
   public static void main(String args[])
   {
      double myCheck = 50.00;
      double yourCheck = 19.95;
      System.out.println("Tips are");
      calcTip(myCheck);
      calcTip(yourCheck);       //declared variable name is yourCheck
                                //declared method name is calcTip
    }
    public static void calcTip(double bill)     //method must be static to call without object from main method
    {
       final double RATE = 0.15;
       double tip;
       tip = bill * RATE;       //variable passed as parameter is bill
       System.out.println("The tip should be at least " + tip);
    }
}
Solution/chapter3/Debugging/FixDebugThree2.java
Solution/chapter3/Debugging/FixDebugThree2.java
// This application displays some math facts
public class FixDebugThree2
{
   public static void main(String args[])
   {
      int a = 2, b = 5, c = 10;
      add(a, b);
      add(b, c);
      subtract(c, a);

   }
   public static void add(int a, int b)     //each parameter must have a datatype
   {
      System.out.println("The sum of " + a +
         " and " + a + " is " + (a + b));
   }
   public static void subtract(int a, int b)       //each parameter must have a datatype
   {
      System.out.println("The difference between  "+    //each string must be enclosed in " "
        a + " and " + b + " is " +  (a - b));       //Difference is calculates using -
   }
}
Solution/chapter3/Debugging/FixDebugThree3.java
Solution/chapter3/Debugging/FixDebugThree3.java
// This application gets a user's name and displays a greeting
import java.util.Scanner;
public class FixDebugThree3
{
   public static void main(String args[])
   {
      String name;
      name = getName();     //statement must be ended by a semicolon
      displayGreeting(name);    //delcared variable is name
   }
   public static String getName()   //void is not required for empty parameters
   {
      String name;
      Scanner input = new Scanner(System.in);
      System.out.print("Enter name ");      //System.out is used to print a statement on the screen
      name = input.nextLine();      //nextLine method is used to read a line
      return name;      //declare variable is name
   }
   public static void displayGreeting(String name)      //each method must have a return type
   {
      System.out.println("Hello, " + name + "!");       //dot operator is required to access a method
   }
}
Solution/chapter3/Debugging/FixDebugThree4.java
Solution/chapter3/Debugging/FixDebugThree4.java
// This program calculates tutition bills
// as credits times rate per credit hour
public class FixDebugThree4
{
   public static void main(String args[])
   {
      int myCredits = 13;
      int yourCredits = 17;
      double rate = 75.84;
      System.out.println("My tuition:");        //each string must be enclosed in " "
      TuitionBill(myCredits, rate);     //method declared is TuitionBill
      System.out.println("Your tuition:");
      TuitionBill(yourCredits, rate);      //method declared is TuitionBill
                                            //rate is used to calculate tution bill
   }
   public static void TuitionBill(int c, double r)
   {
      System.out.println("Total due " + (r / c));   //each string must be enclosed in " "
   }
}
Solution/chapter3/Gamezone/Card.java
Solution/chapter3/Gamezone/Card.java
public class Card {
    char suit;
    int value;
    public Card(char suit, int value) {
        this.suit = suit;
        this.value = value;
    }
    public char getSuit() {
        return suit;
    }
    public int getValue() {
        return value;
    }
    public void setSuit(char suit) {
        this.suit = suit;
    }
    public void setValue(int value) {
        this.value = value;
    }

}
Solution/chapter3/Gamezone/MyCharacter.java
Solution/chapter3/Gamezone/MyCharacter.java
public class MyCharacter {

    String name;
    double health;
    int lives;
    public MyCharacter(String name, double health, int lives) {
        this.name = name;
        this.health = health;
        this.lives = lives;
    }
    public double getHealth() {
        return health;
    }
    public int getLives() {
        return lives;
    }
    public String getName() {
        return name;
    }
    public void setHealth(double health) {
        this.health = health;
    }
    public void setLives(int lives) {
        this.lives = lives;
    }
    public void setName(String name) {
        this.name = name;
    }

}
Solution/chapter3/Gamezone/PickTwoCards.java
Solution/chapter3/Gamezone/PickTwoCards.java
public class PickTwoCards {

    public static void main(String[] args) {
        final int CARDS_IN_SUIT = 13;

        char mySuit1 = 's';
        int myValue1 = ((int) (Math.random() * 100) % CARDS_IN_SUIT + 1);

        Card card1 = new Card(mySuit1, myValue1);
        System.out.println("First card is :" + card1.getValue() + card1.getSuit());

        char mySuit2 = 'h';
        int myValue2 = ((int) (Math.random() * 100) % CARDS_IN_SUIT + 1);

        Card card2 = new Card(mySuit2, myValue2);
        System.out.println("Second card is :" + card2.getValue() + card2.getSuit());
    }
}
Solution/chapter3/Gamezone/TwoCharacters.java
Solution/chapter3/Gamezone/TwoCharacters.java
public class TwoCharacters {

    public static void displayCharacter(MyCharacter character){
        System.out.println("Name: " + character.getName());
        System.out.println("Lives: " + character.getLives());
        System.out.println("Health: " + character.getHealth());
        System.out.println();
    }

    public static void main(String[] args) {

        MyCharacter character1 = new MyCharacter("Character1", 100, 5);
        displayCharacter(character1);
        MyCharacter character2 = new MyCharacter("character2", 150, 7);
        displayCharacter(character2);
    }
}
Solution/chapter3/Ques10/JobPricing.java
Solution/chapter3/Ques10/JobPricing.java
import java.util.Scanner;
public class JobPricing {

    public static double calcCost(int workHours, int travelHours){
        return (workHours * 35) + (travelHours * 12);
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter job name: ");
        String name = scan.nextLine();

        System.out.println("Enter cost of materials: ");
        double costMaterial = Double.parseDouble(scan.nextLine());

        System.out.println("Enter number of hours worked required: ");
        int workHours = Integer.parseInt(scan.nextLine());

        System.out.println("Enter number of hours travel required: ");
        int travelHours = Integer.parseInt(scan.nextLine());

        double jobCost = calcCost(workHours, travelHours);
        System.out.println("Job " + name + " estimated cost is $" + jobCost);
    }
}
Solution/chapter3/Ques11/Sandwich.java
Solution/chapter3/Ques11/Sandwich.java
public class Sandwich {

    String mainIngredient;
    String breadType;
    double price;
    public String getBreadType() {
        return breadType;
    }
    public String getMainIngredient() {
        return mainIngredient;
    }
    public double getPrice() {
        return price;
    }
    public void setBreadType(String breadType) {
        this.breadType = breadType;
    }
    public void setMainIngredient(String mainIngredient) {
        this.mainIngredient = mainIngredient;
    }
    public void setPrice(double price) {
        this.price = price;
    }

}
Solution/chapter3/Ques11/TestSandwich.java
Solution/chapter3/Ques11/TestSandwich.java
import java.util.Scanner;
public class TestSandwich {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Sandwich obj = new Sandwich();

        System.out.println("Enter main ingredient: ");
        String ingredient = scan.nextLine();
        System.out.println("Enter bread type: ");
        String bread = scan.nextLine();
        System.out.println("Enter price: ");
        double price = Double.parseDouble(scan.nextLine());
        obj.setMainIngredient(ingredient);
        obj.setBreadType(bread);
        obj.setPrice(price);

        System.out.println("Sandwich with main ingredient " + obj.getMainIngredient()
            + " bread type " + obj.getBreadType() + " costs $" + obj.getPrice());
    }
}
Solution/chapter3/Ques12/ShowStudent.java
Solution/chapter3/Ques12/ShowStudent.java
public class ShowStudent {

    public static void main(String[] args) {
        Student obj = new Student();
        obj.setID(1234);
        obj.setCreditHours(5);
        obj.setPoints(30);
        obj.setGrades();
        obj.display();
    }
}
Solution/chapter3/Ques12/ShowStudent2.java
Solution/chapter3/Ques12/ShowStudent2.java
public class ShowStudent2 {
    public static void main(String[] args) {
        Student obj = new Student();
        obj.display();
    }
}
Solution/chapter3/Ques12/Student.java
Solution/chapter3/Ques12/Student.java
public class Student {

    int ID;
    int creditHours;
    int points;
    double grades;
    public Student() {
        ID = 9999;
        points = 12;
        creditHours = 3;
        setGrades();
    } 

    public void setCreditHours(int creditHours) {
        this.creditHours = creditHours;
    }
    public void setID(int ID) {
        this.ID = ID;
    }
    public void setPoints(int points) {
        this.points = points;
    }

    public void setGrades(){
        grades = points/creditHours;
    }
    public void display(){
        System.out.println("Student ID " + ID + " with credit hours " + creditHours + " and points earned " + points + " have grades " + grades);
    }
}
Solution/chapter3/Ques13/Lease.java
Solution/chapter3/Ques13/Lease.java
public class Lease {

    String tenantName;
    int apartmentNumber;
    double monthlyRent;
    int leaseMonths;
    public Lease() {
        this.tenantName = "XXX";
        this.apartmentNumber = 0;
        this.monthlyRent = 1000;
        this.leaseMonths = 12;
    }
    public int getApartmentNumber() {
        return apartmentNumber;
    }
    public int getLeaseMonths() {
        return leaseMonths;
    }
    public double getMonthlyRent() {
        return monthlyRent;
    }
    public String getTenantName() {
        return tenantName;
    }
    public void setApartmentNumber(int apartmentNumber) {
        this.apartmentNumber = apartmentNumber;
    }
    public void setLeaseMonths(int leaseMonths) {
        this.leaseMonths = leaseMonths;
    }
    public void setMonthlyRent(double monthlyRent) {
        this.monthlyRent = monthlyRent;
    }
    public void setTenantName(String tenantName) {
        this.tenantName = tenantName;
    }

    public void addPetFee(){
        this.monthlyRent += 10;
        Lease.explainPetPolicy();
    }

    public static void explainPetPolicy(){
        System.out.println("Thi...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here