1. Suppose that you have created a program with only the following variables. int x = 2; int y = 3; Suppose that you also have a method with the following header: public static void mathMethod(int x) Which of the following method calls are legal? a. mathMethod(x); Legal b. mathMethod(y); Legal c. mathMethod(x, y); Illegal d. mathMethod(x + y); Legal e. mathMethod(12L); Illegal f. mathMethod(12); Legal g. mathMethod(12.2); Illegal h. mathMethod(); Illegal i. mathMethod(a); Illegal j. mathMethod(a / x); Illegal
  2. Suppose that you have created a program with only the following variables. int age = 34; int weight = 180; double height = 5.9; Suppose that you also have a method with the following header: public static void calculate(int age, double size) Which of the following method calls are legal? a. calculate(age, weight); Legal b. calculate(age, height); Legal c. calculate(weight, height); Legal d. calculate(height, age); Illegal e. calculate(45.5, 120); Illegal f. calculate(12, 120.2); Legal g. calculate(age, size); Illegal h. calculate(2, 3); Legal i. calculate(age); Illegal j. calculate(weight, weight); Legal
  3. Suppose that a class named Bicycle contains a private nonstatic integer named height, a public nonstatic String named model, and a public static integer named wheels. Which of the following are legal statements in a class named BicycleDemo that has instantiated an object as Bicycle myBike = new Bicycle();? a. myBike.height = 26; Illegal b. myBike.model = “Cyclone”; Legal c. myBike.wheels = 3; Legal d. myBike.model = 108; Illegal e. Bicycle.height = 24; Illegal f. Bicycle.model = “Hurricane”; Illegal g. Bicycle.int = 3; Illegal h. Bicycle.model = 108; Illegal i. Bicycle.wheels = 2; Legal j. Bicycle yourBike = myBike; Legal
    1. Create an application named NumbersDemo whose main() method holds two integer variables. Assign values to the variables. In turn, pass each value to methods named displayTwiceTheNumber(), displayNumberPlusFive(), and displayNumberSquared(). Create each method to perform the task its name implies. Save the application as NumbersDemo.java.

      public class NumbersDemo { public static void main (String args[]) { int num1 = 4, num2 = 33; displayTwiceTheNumber(num1); displayNumberPlusFive(num1); displayNumberSquared(num1); displayTwiceTheNumber(num2); displayNumberPlusFive(num2); displayNumberSquared(num2); } public static void displayTwiceTheNumber(int n) { final int FACTOR = 2; System.out.println(n + " times " + FACTOR + " is " + (n * FACTOR)); } public static void displayNumberPlusFive(int n) { final int FACTOR = 5; System.out.println(n + " plus " + FACTOR + " is " + (n + FACTOR)); } public static void displayNumberSquared(int n) { System.out.println(n + " squared is " + (n * n)); } }
    2. Modify the NumbersDemo class to accept the values of the two integers from a user at the keyboard. Save the file as NumbersDemo2.java.

      import java.util.Scanner; public class NumbersDemo2 { public static void main (String args[]) { Scanner kb = new Scanner(System.in); int num1, num2; System.out.print("Enter an integer >> "); num1 = kb.nextInt(); System.out.print("Enter another integer >> "); num2 = kb.nextInt(); displayTwiceTheNumber(num1); displayNumberPlusFive(num1); displayNumberSquared(num1); displayTwiceTheNumber(num2); displayNumberPlusFive(num2); displayNumberSquared(num2); } public static void displayTwiceTheNumber(int n) { final int FACTOR = 2; System.out.println(n + " times " + FACTOR + " is " + (n * FACTOR)); } public static void displayNumberPlusFive(int n) { final int FACTOR = 5; System.out.println(n + " plus " + FACTOR + " is " + (n + FACTOR)); } public static void displayNumberSquared(int n) { System.out.println(n + " squared is " + (n * n)); } }
    1. Create an application named Percentages whose main() method holds two double variables. Assign values to the variables. Pass both variables to a method named computePercent() that displays the two values and the value of the first number as a percentage of the second one. For example, if the numbers are 2.0 and 5.0, the method should display a statement similar to “2.0 is 40 percent of 5.0.” Then call the method a second time, passing the values in reverse order. Save the application as Percentages.java.

      public class Percentages { public static void main (String args[]) { double num1 = 2.0, num2 = 5.0; computePercent(num1, num2); computePercent(num2, num1); } public static void computePercent(double x, double y) { System.out.println(x + " is " + (x / y) * 100 + " percent of " + y); } }
    2. Modify the Percentages class to accept the values of the two doubles from a user at the keyboard. Save the file as Percentages2.java.

      import java.util.Scanner; public class Percentages2 { public static void main (String args[]) { double num1, num2; Scanner kb = new Scanner(System.in); System.out.print("Enter a double >> "); num1 = kb.nextDouble(); System.out.print("Enter another double >> "); num2 = kb.nextDouble(); computePercent(num1, num2); computePercent(num2, num1); } public static void computePercent(double x, double y) { System.out.println(x + " is " + (x / y) * 100 + " percent of " + y); } }
  4. To encourage good grades, Hermosa High School has decided to award each student a bookstore credit that is 10 times the student’s grade point average. In other words, a student with a 3.2 grade point average receives a $32 credit. Create a class that prompts a student for a name and grade point average, and then passes the values to a method that displays a descriptive message. The message uses the student’s name, echoes the grade point average, and computes and displays the credit. Save the application as BookstoreCredit.java.

    import java.util.Scanner; public class BookstoreCredit { public static void main (String args[]) { String name; double gpa; Scanner input = new Scanner(System.in); System.out.print("Enter your name >> "); name = input.nextLine(); System.out.print("Enter your gpa >>"); gpa = input.nextDouble(); computeDiscount(name, gpa); } public static void computeDiscount(String name, double gpa) { double discount; final double FACTOR = 10; discount = gpa * FACTOR; System.out.println(name + ", your GPA is " + gpa + ", so your discount is $" + discount); } public static void convertToLiters(int gallons) { double liters; final double LITER_FACTOR = 3.7854; liters = gallons * LITER_FACTOR; System.out.println(gallons + " gallons is " + liters + " liters"); } }
  5. There are 12 inches in a foot and 3 feet in a yard. Create a class named InchConversion. Its main() method accepts a value in inches from a user at the keyboard, and in turn passes the entered value to two methods. One converts the value from inches to feet, and the other converts the same value from inches to yards. Each method displays the results with appropriate explanation. Save the application as InchConversion.java.

    import java.util.Scanner; public class InchConversion { public static void main (String args[]) { int inches; Scanner input = new Scanner(System.in); System.out.print("Enter inches >> "); inches = input.nextInt(); convertToFeet(inches); convertToYards(inches); } public static void convertToFeet(int inches) { double feet; final double INCHES_IN_FT = 12; feet = inches / INCHES_IN_FT; System.out.println(inches + " inches is " + feet + " feet"); } public static void convertToYards(int inches) { double yards; final double INCHES_IN_YD = 36; yards = inches / INCHES_IN_YD; System.out.println(inches + " inches is " + yards + " yards"); } }
  6. Assume that a gallon of paint covers about 350 square feet of wall space. Create an application with a main() method that prompts the user for the length, width, and height of a rectangular room. Pass these three values to a method that does the following: • Calculates the wall area for a room • Passes the calculated wall area to another method that calculates and returns the number of gallons of paint needed • Displays the number of gallons needed • Computes the price based on a paint price of $32 per gallon, assuming that the painter can buy any fraction of a gallon of paint at the same price as a whole gallon • Returns the price to the main() method The main() method displays the final price. For example, the cost to paint a 15-by-20-foot room with 10-foot ceilings is $64. Save the application as PaintCalculator.java.
    import java.util.Scanner; public class PaintCalculator { public static void main (String args[]) { double length, width, height; double price; Scanner kb = new Scanner(System.in); System.out.print("Enter the room's length >> "); length = kb.nextDouble(); System.out.print("Enter the room's width >> "); width = kb.nextDouble(); System.out.print("Enter the room's height >> "); height = kb.nextDouble(); price = computeArea(length, width, height); System.out.println("The price to paint the room is $" + price); } public static double computeArea(double length, double width, double height) { final double PRICE_GALLON = 32; double area = length * height * 2 + width * height * 2; double gallons; double price; gallons = computeGallons(area); System.out.println("You will need " + gallons + " gallons"); price = gallons * PRICE_GALLON; return price; } public static double computeGallons(double area) { final int SQFT_PER_GAL = 350; double gallons = area / SQFT_PER_GAL; return gallons; } }
  7. The Harrison Group Life Insurance company computes annual policy premiums based on the age the customer turns in the current calendar year. The premium is computed by taking the decade of the customer’s age, adding 15 to it, and multiplying by 20. For example, a 34-year-old would pay $360, which is calculated by adding the decades (3) to 15, and then multiplying by 20. Write an application that prompts a user for the current year and a birth year. Pass both to a method that calculates and returns the premium amount, and then display the returned amount. Save the application as Insurance.java.

    import java.util.Scanner; class Insurance { public static void main (String args[]) { int currYear; int birthYear; int premium; Scanner input = new Scanner(System.in); System.out.print("Enter the current year >> "); currYear = input.nextInt(); System.out.print("Enter the birth year >> "); birthYear = input.nextInt(); premium = calculatePremium(currYear, birthYear); System.out.println("The premium is $" + premium); } public static int calculatePremium(int curr, int birth) { final int ADDITION_FACTOR = 15; final int MULTIPLICATION_FACTOR = 20; int age = curr - birth; int decade = age / 10; int premium = (ADDITION_FACTOR + decade) * MULTIPLICATION_FACTOR; return premium; } }
  8. Herbert’s Home Repair estimates each job cost as the cost of materials plus $35 per hour while on the job, plus $12 per hour for travel time to the job site. Create a class that contains a main() method that prompts the user for the name of a job (for example, Smith bathroom remodel), the cost of materials, the number of hours of work required, and the number of hours travel time. Pass the numeric data to a method that computes estimate for the job and returns the computed value to the main() method where the job name and estimated price are displayed. Save the program as JobPricing.java.

    import java.util.Scanner; class JobPricing { public static void main(String[] args) { String description; double materials; double hoursOnJob; double hoursTraveling; double price; Scanner input = new Scanner(System.in); System.out.print("Enter job descriptpon >> "); description = input.nextLine(); System.out.print("Enter cost of materials >> "); materials = input.nextDouble(); System.out.print("Enter hours on the job work >> "); hoursOnJob = input.nextDouble(); System.out.print("Enter hours traveling >> "); hoursTraveling = input.nextDouble(); price = computePrice(materials, hoursOnJob, hoursTraveling); System.out.println("The price for " + description + " is $" + price); } public static double computePrice(double materials, double hours, double travel) { double price; final double RATE = 35; final double TRAVEL_RATE = 12; price = materials + hours * RATE + travel * TRAVEL_RATE; return price; } }
    1. Create a class named Sandwich. Data fields include a String for the main ingredient (such as tuna), a String for bread type (such as wheat), and a double for price (such as 4.99). Include methods to get and set values for each of these fields. Save the class as Sandwich.java.

      class Sandwich { // the private data members private String mainIngredient; private String bread; private double price; // the public get and set methods public void setMainIngredient(String ingredient) { mainIngredient = ingredient; } public String getMainIngredient() { return mainIngredient; } public void setBread(String breadType) { bread = breadType; } public String getBread() { return bread; } public void setPrice(double amt) { price = amt; } public double getPrice() { return price; } }
    2. Create an application named TestSandwich that instantiates one Sandwich object and demonstrates the use of the set and get methods. Save this application as TestSandwich.java.

      class TestSandwich { public static void main (String args[]) { Sandwich sandwich = new Sandwich(); sandwich.setMainIngredient("tuna"); sandwich.setBread("wheat"); sandwich.setPrice(4.99); System.out.println("You have ordered a " + sandwich.getMainIngredient() + " sandwich on " + sandwich.getBread() + " bread, and the price is " + sandwich.getPrice()); } }
    1. Create a class named Student that has fields for an ID number, number of credit hours earned, and number of points earned. (For example, many schools compute grade point averages based on a scale of 4, so a three-credit-hour class in which a student earns an A is worth 12 points.) Include methods to assign values to all fields. A Student also has a field for grade point average. Include a method to compute the grade point average field by dividing points by credit hours earned. Write methods to display the values in each Student field. Save this class as Student.java.

      class Student { // the private data members private int idNumber; private int hours; private int points; // Constructor added in part c Student() { idNumber = 9999; points = 12; hours = 3; } // end of constructor added in part c // the public get and set methods public void setIDnumber(int number) { idNumber = number; } public int getIDnumber() { return idNumber; } public void setHours(int number) { hours = number; } public int getHours() { return hours; } public void setPoints(int number) { points = number; } public int getPoints() { return points; } // methods to display the fields public void showIDnumber() { System.out.println("ID Number is: " + idNumber); } public void showHours() { System.out.println("Credit Hours: " + hours); } public void showPoints() { System.out.println("Points Earned: " + points); } public double getGradePoint() { return (points * 1.0 / hours); // simple integer division will truncate the decimal places } }
    2. Write a class named ShowStudent that instantiates a Student object from the class you created and assign values to its fields. Compute the Student grade point average, and then display all the values associated with the Student. Save the application as ShowStudent.java.

      class ShowStudent { public static void main (String args[]) { Student pupil = new Student(); pupil.setIDnumber(234); pupil.setPoints(47); pupil.setHours(15); pupil.showIDnumber(); pupil.showPoints(); pupil.showHours(); System.out.println("The grade point average is " + pupil.getGradePoint()); } }
    3. Create a constructor for the Student class you created. The constructor should initialize each Student’s ID number to 9999, his or her points earned to 12, and credit hours to 3 (resulting in a grade point average of 4.0). Write a program that demonstrates that the constructor works by instantiating an object and displaying the initial values. Save the application as ShowStudent2.java.

      class ShowStudent2 { public static void main (String args[]) { Student pupil = new Student(); pupil.showIDnumber(); pupil.showPoints(); pupil.showHours(); System.out.println("The grade point average is " + pupil.getGradePoint()); } }
    1. Create a class named Lease with fields that hold an apartment tenant’s name, apartment number, monthly rent amount, and term of the lease in months. Include a constructor that initializes the name to “XXX”, the apartment number to 0, the rent to 1000, and the term to 12. Also include methods to get and set each of the fields. Include a nonstatic method named addPetFee() that adds $10 to the monthly rent value and calls a static method named explainPetPolicy() that explains the pet fee. Save the class as Lease.java.

      class Lease { private String name; private int aptNumber; private double rent; private int term; private static final int FEE = 10; public Lease() { name = "XXX"; aptNumber = 0; rent = 1000; term = 12; } public void setName(String tenant) { name = tenant; } public void setAptNumber(int apt) { aptNumber = apt; } public void setRent(double monthRent) { rent = monthRent; } public void setTerm(int t) { term = t; } public String getName() { return name; } public int getAptNumber() { return aptNumber; } public double getRent() { return rent; } public int getTerm() { return term; } public void addPetFee() { rent = rent + FEE; explainPetPolicy(); } public static void explainPetPolicy() { System.out.println("\nA pet fee of $" + FEE + " is addd to the monthly rent."); } }
    2. Create a class named TestLease whose main() method declares four Lease objects. Call a getData() method three times. Within the method, prompt a user for values for each field for a Lease, and return a Lease object to the main() method where it is assigned to one of main()’s Lease objects. Do not prompt the user for values for the fourth Lease object, but let it continue to hold the default values. Then, in main(), pass one of the Lease objects to a showValues() method that displays the data. Then call the addPetFee() method using the passed Lease object and confirm that the fee explanation statement is displayed. Next, call the showValues() method for the Lease object again and confirm that the pet fee has been added to the rent. Finally, call the showValues() method with each of the other three objects; confirm that two hold the values you supplied as input and one holds the constructor default values. Save the application as TestLease.java.

      import java.util.Scanner; class TestLease { public static void main (String args[]) { Lease lease1; Lease lease2; Lease lease3; Lease lease4 = new Lease(); lease1 = getData(); lease2 = getData(); lease3 = getData(); showValues(lease1); lease1.addPetFee(); showValues(lease1); showValues(lease2); showValues(lease3); showValues(lease4); } public static void showValues(Lease ls) { System.out.println("\n\nYour lease results:" + "\nName : " + ls.getName() + "\nApartment : " + ls.getAptNumber() + "\nRent : " + ls.getRent() + "\nTerm : " + ls.getTerm()); } public static Lease getData() { String name; int apt; double rent; int term; Scanner input = new Scanner(System.in); System.out.print("\nEnter lessee name >> "); name = input.nextLine(); System.out.print("Enter apartment number >> "); apt = input.nextInt(); System.out.print("Enter rent >> "); rent = input.nextDouble(); System.out.print("Enter lease term in months >> "); term = input.nextInt(); input.nextLine(); Lease temp = new Lease(); temp.setName(name); temp.setAptNumber(apt); temp.setRent(rent); temp.setTerm(term); return temp; } }