1. Write an application that asks a user to enter an integer. Display a statement that indicates whether the integer is even or odd. Save the file as EvenOdd.java.

    import java.util.Scanner; class EvenOdd { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number; System.out.print("Enter a number >> "); number = input.nextInt(); if(isEven(number)) System.out.println(number + " is even"); else System.out.println(number + " is odd"); } public static boolean isEven(int number) { boolean result; if(number % 2 == 1) result = false; else result = true; return result; } }
  2. Write an application that asks a user to enter three integers. Display them in ascending and descending order. Save the file as AscendingAndDescending.java.

    import java.util.Scanner; public class AscendingAndDescending { public static void main(String[] args) { int num1, num2, num3; int low, med, high; Scanner keyboard = new Scanner(System.in); System.out.print("Enter an integer... "); num1 = keyboard.nextInt(); System.out.print("And another... "); num2 = keyboard.nextInt(); System.out.print("And just one more... "); num3 = keyboard.nextInt(); if(num1 <= num2 && num1 <= num3) { low = num1; if(num2 <= num3) { med = num2; high = num3; } else { med = num3; high = num2; } } else { if(num2 <= num1 && num2 <= num3) { low = num2; if(num1 <= num3) { med = num1; high = num3; } else { med = num3; high = num1; } } else { low = num3; if(num1 <= num2) { med = num1; high = num2; } else { med = num2; high = num1; } } } System.out.println("Ascending: " + low + " " + med + " " + high); System.out.println("Descending: " + high + " " + med + " " + low); } }
    1. Write an application for the Shady Rest Hotel; the program determines the price of a room. Ask the user to choose 1 for a queen bed, 2 for a king, or 3 for a king and a pullout couch. The output echoes the input and displays the price of the room: $125 for queen, $139 for king, and $165 for suite with king bed and a pullout couch. If the user enters an invalid code, display an appropriate message and set the price to 0. Save the file as ShadyRestRoom.java.

      import java.util.Scanner; public class ShadyRestRoom { public static void main (String args[]) { int selection; int price; String result; final int QUEEN = 1, KING = 2, SUITE = 3; final int QPRICE = 125, KPRICE = 139, SPRICE = 165; final String QSTRING = "Queen bed", KSTRING = "King bed", SSTRING = "Suite with a king bed and pull-out couch", INVALIDSTRING = "an invalid option"; Scanner in = new Scanner(System.in); System.out.println("\t\n\nMenu\n"); System.out.println("(" + QUEEN + ") " + QSTRING); System.out.println("(" + KING + ") " + KSTRING); System.out.println("(" + SUITE + ") " + SSTRING); System.out.print("Enter Selection (1, 2, or 3) >> "); selection = in.nextInt(); if(selection == QUEEN) { result = QSTRING; price = QPRICE; } else if(selection == KING) { result = KSTRING; price = KPRICE; } else if (selection == SUITE) { result = SSTRING; price = SPRICE; } else { result = INVALIDSTRING; price = 0; } System.out.println("You selected " + result + " $" + price); } }
    2. Add a prompt to the ShadyRestRoom application to ask the user to specify a (1) lake view or a (2) park view, but ask only if the bed size entry is valid. Add $15 to the price of any room with a lake view. If the view value is invalid, display an appropriate message and assume that the price is for a room with a lake view. Save the file as ShadyRestRoom2.java.

      import java.util.Scanner; public class ShadyRestRoom2 { public static void main (String args[]) { int selection; int price; String result; String view = "no"; final int QUEEN = 1, KING = 2, SUITE = 3; final int QPRICE = 125, KPRICE = 139, SPRICE = 165; final String QSTRING = "Queen bed", KSTRING = "King bed", SSTRING = "Suite with a king bed and pull-out couch", INVALIDSTRING = "an invalid option"; final int LAKE = 1, PARK = 2; final int LPREMIUM = 15; final String LSTRING = "a lake", PSTRING = "a park", VIEW_ERRORSTRING = "an invalid view, so using lake"; Scanner in = new Scanner(System.in); System.out.println("\t\n\nMenu\n"); System.out.println("(" + QUEEN + ") " + QSTRING); System.out.println("(" + KING + ") " + KSTRING); System.out.println("(" + SUITE + ") " + SSTRING); System.out.print("Enter Selection (1, 2, or 3) >> "); selection = in.nextInt(); if(selection == QUEEN) { result = QSTRING; price = QPRICE; } else if(selection == KING) { result = KSTRING; price = KPRICE; } else if (selection == SUITE) { result = SSTRING; price = SPRICE; } else { result = INVALIDSTRING; price = 0; } if(price != 0) { System.out.println("Please choose a view:"); System.out.println("(" + LAKE + ") " + LSTRING); System.out.println("(" + PARK + ") " + PSTRING); System.out.print("Enter Selection (1 or 2) >> "); selection = in.nextInt(); if(selection == LAKE) { view = LSTRING; price += LPREMIUM; } else if(selection == PARK) { view = PSTRING; } else { price += LPREMIUM; view = VIEW_ERRORSTRING; } } System.out.println("You selected " + result + " with " + view + " view for $" + price); } }
  3. Write a program for Horizon Phones, a provider of cellular phone service. Prompt a user for maximum monthly values for talk minutes used, text messages sent, and gigabytes of data used, and then recommend the best plan for the customer’s needs. A customer who needs fewer than 500 minutes of talk and no text or data should accept Plan A at $49 per month. A customer who needs fewer than 500 minutes of talk and any text messages should accept Plan B at $55 per month. A customer who needs 500 or more minutes of talk and no data should accept either Plan C for up to 100 text messages at $61 per month or Plan D for 100 text messages or more at $70 per month. A customer who needs any data should accept Plan E for up to 3 gigabytes at $79 or Plan F for 3 gigabytes or more at $87. Save the file as CellPhoneService.java.

    import javax.swing.*; public class CellPhoneService { public static void main (String args[]) { int talk; int texts; int data; final int TALK_MIN = 500; final int TEXTS_MIN = 100; final int DATA_MIN = 2; final int PRICEA = 49; final int PRICEB = 55; final int PRICEC = 61; final int PRICED = 70; final int PRICEE = 79; final int PRICEF = 87; String entry, message; int price; String plan; entry = JOptionPane.showInputDialog(null, "Enter talk minutes needed"); talk = Integer.parseInt(entry); entry = JOptionPane.showInputDialog(null, "Enter text messages needed"); texts = Integer.parseInt(entry); entry = JOptionPane.showInputDialog(null, "Enter gigabytes of data needed"); data = Integer.parseInt(entry); if(data > 0) if(data <= DATA_MIN) { plan = "E"; price = PRICEE; } else { plan = "F"; price = PRICEF; } else if(talk < TALK_MIN) if(texts == 0 && data == 0) { plan = "A"; price = PRICEA; } else { plan = "B"; price = PRICEB; } else if(texts < TEXTS_MIN) { plan = "C"; price = PRICEC; } else { plan = "D"; price = PRICED ; } message = "Plan " + plan + " $" + price + " per month"; JOptionPane.showMessageDialog(null, message); } }
    1. Write an application that prompts a user for a month, day, and year. Display a message that specifies whether the entered date is (1) not this year, (2) in an earlier month this year, (3) in a later month this year, or (4) this month. Save the file as PastPresentFuture.java.

      import java.util.*; import java.time.*; public class PastPresentFuture { public static void main (String args[]) { LocalDate today = LocalDate.now(); int mo, da, yr; int todayMo, todayDa, todayYr; Scanner input = new Scanner(System.in); todayMo = today.getMonthValue(); todayDa = today.getDayOfMonth(); todayYr = today.getYear(); System.out.print("Enter a month >> "); mo = input.nextInt(); System.out.print("Enter a day >> "); da = input.nextInt(); System.out.print("Enter a year (four digits) >> "); yr = input.nextInt(); if(yr != todayYr) System.out.println(yr + " is not this year"); else if(mo < todayMo) System.out.println(mo + " was a month earlier this year"); else if(mo > todayMo) System.out.println(mo + " is a month later this year"); else System.out.println(mo + " is this month"); } }
    2. Use the web to learn how to use the LocalDate Boolean methods isBefore(), isAfter(), and equals(). Use your knowledge to write a program that prompts a user for a month, day, and year, and then displays a message specifying whether the entered day is in the past, the current date, or in the future. Save the file as PastPresentFuture2.java.

      import java.util.*; import java.time.*; public class PastPresentFuture2 { public static void main (String args[]) { LocalDate today = LocalDate.now(); LocalDate enteredDate; int mo, da, yr; int todayMo, todayDa, todayYr; Scanner input = new Scanner(System.in); System.out.print("Enter a month >> "); mo = input.nextInt(); System.out.print("Enter a day >> "); da = input.nextInt(); System.out.print("Enter a year (four digits) >> "); yr = input.nextInt(); enteredDate = LocalDate.of(yr, mo, da); if(enteredDate.isBefore(today)) System.out.println(enteredDate + " is in the past"); else if(enteredDate.equals(today)) System.out.println(enteredDate + " is today"); else System.out.println(enteredDate + " is in the future"); } }
  4. Acme Parts runs a small factory and employs workers who are paid one of three hourly rates depending on their shift: first shift, $17 per hour; second shift, $18.50 per hour; third shift, $22 per hour. Each factory worker might work any number of hours per week; any hours greater than 40 are paid at one and one-half times the usual rate. In addition, second- and third-shift workers can elect to participate in the retirement plan for which 3% of the worker’s gross pay is deducted from the paychecks. Write a program that prompts the user for hours worked and shift, and, if the shift is 2 or 3, whether the worker elects the retirement. Display: (1) the hours worked, (2) the shift, (3) the hourly pay rate, (4) the regular pay, (5) overtime pay, (6) the total of regular and overtime pay, and (7) the retirement deduction, if any, and (8) the net pay. Save the file as AcmePay.java.

    import javax.swing.*; public class AcmePay { public static void main(String[] args) throws Exception { String entry, message; int shift; double hoursWorked; double regularPay, overtimePay, totalPay; double payRate; double retDeduction = 0; int retOption = 0; final double PAY1 = 17.00; final double PAY2 = 18.50; final double PAY3 = 22.00; final int FULLWEEK = 40; final double OT_RATE = 1.5; final double RET_RATE = 0.03; entry = JOptionPane.showInputDialog(null, "Please enter shift - 1, 2, or 3"); shift = Integer.parseInt(entry); entry = JOptionPane.showInputDialog(null, "Please enter hours worked"); hoursWorked = Double.parseDouble(entry); if(shift == 1) payRate = PAY1; else if(shift == 2) payRate = PAY2; else payRate = PAY3; if(hoursWorked > FULLWEEK) { regularPay = FULLWEEK * payRate; overtimePay = (hoursWorked - FULLWEEK) * OT_RATE * payRate; } else { regularPay = hoursWorked * payRate; overtimePay = 0.0; } totalPay = regularPay + overtimePay; if(shift == 2 || shift == 3) { entry = JOptionPane.showInputDialog(null, "Do you want to participate in the retirement plan?\n" + " Enter 1 for Yes and 2 for No."); retOption = Integer.parseInt(entry); if(retOption == 1) retDeduction = totalPay * RET_RATE; } message = "\nHours worked is " + hoursWorked + "\nHourly pay rate is " + payRate + "\nRegular pay is " + regularPay + "\nOvertime pay is " + overtimePay + "\nRetirement deduction is " + retDeduction + "\nNet pay is...................." + (totalPay - retDeduction); JOptionPane.showMessageDialog(null, message); } }
  5. Create a class that holds data about a job applicant. Include a name, a phone number, and four Boolean fields that represent whether the applicant is skilled in each of the following areas: word processing, spreadsheets, databases, and graphics. Include a constructor that accepts values for each of the fields. Also include a get method for each field. Create an application that instantiates several job applicant objects and pass each in turn to a Boolean method that determines whether each applicant is qualified for an interview. Then, in the main() method, display an appropriate method for each applicant. A qualified applicant has at least three of the four skills. Save the files as JobApplicant.java and TestJobApplicants.java.

    import java.util.Scanner; public class TestJobApplicants { public static void main(String[] args) { JobApplicant app1 = new JobApplicant("Johnson", "312-345-9875", true, false, true, false); JobApplicant app2 = new JobApplicant("Kermit", "312-543-1275", true, false, false, false); JobApplicant app3 = new JobApplicant("Lawrence", "608-288-09125", true, false, true, true); JobApplicant app4 = new JobApplicant("Mitchell", "815-288-3881", true, true, true, true); String qualifiedMsg = "is qalified for an interview "; String notQualifiedMsg = "is not qualified for an interview at this time "; if(isQualified(app1)) display(app1, qualifiedMsg); else display(app1, notQualifiedMsg); if(isQualified(app2)) display(app2, qualifiedMsg); else display(app2, notQualifiedMsg); if(isQualified(app3)) display(app3, qualifiedMsg); else display(app3, notQualifiedMsg); if(isQualified(app4)) display(app4, qualifiedMsg); else display(app4, notQualifiedMsg); } public static boolean isQualified(JobApplicant app) { int count = 0; boolean isQual; final int MIN_SKILLS = 3; if(app.getHasWordSkill()) count = count + 1; if(app.getHasSpreadsheetSkill()) count = count + 1; if(app.getHasDatabaseSkill()) count = count + 1; if(app.getHasGraphicsSkill()) count = count + 1; if(count >= MIN_SKILLS) isQual = true; else isQual = false; return isQual; } public static void display(JobApplicant app, String msg) { System.out.println(app.getName() + " " + msg + " Phone: " + app.getPhone()); } }
  6. Create an Automobile class for a dealership. Include fields for an ID number, make, model, color, year, and miles per gallon. Include get and set methods for each field. Do not allow the ID to be negative or more than 9999; if it is, set the ID to 0. Do not allow the year to be earlier than 2005 or later than 2019; if it is, set the year to 0. Do not allow the miles per gallon to be less than 10 or more than 60; if it is, set the miles per gallon to 0. Include a constructor that accepts arguments for each field value and uses the set methods to assign the values. Write an application that declares several Automobile objects and demonstrates that all the methods work correctly. Save the files as Automobile.java and TestAutomobiles.java.

    public class Automobile { private int id; private String make; private String model; private String color; private int year; private double mpg; public Automobile(int id, String make, String model, String color, int year, double mpg) { setId(id); setMake(make); setModel(model); setColor(color); setYear(year); setMpg(mpg); } public void setId(int id) { final int MAX_ID = 9999; if(id < 0 || id > MAX_ID) this.id = 0; else this.id = id; } public void setMake(String make) { this.make = make; } public void setModel(String model) { this.model = model; } public void setColor(String color) { this.color = color; } public void setYear(int yr) { final int MAX_YEAR = 2019; final int MIN_YEAR = 2005; if(yr < MIN_YEAR || yr > MAX_YEAR) year = 0; else year = yr; } public void setMpg(double mpg) { final double MIN_MPG = 10; final double MAX_MPG = 60; if(mpg < MIN_MPG || mpg > MAX_MPG) this.mpg = 0; else this.mpg = mpg; } public int getId() { return id; } public String getMake() { return make; } public String getModel() { return model; } public String getColor() { return color; } public int getYear() { return year; } public double getMpg() { return mpg; } }
    public class TestAutomobiles { public static void main(String[] args) { Automobile auto1 = new Automobile(1451, "Chevrolet", "Camaro", "red", 2010, 24.5); Automobile auto2 = new Automobile(145188, "Ford", "Focus", "white", 2020, 75); display(auto1, "good declaration"); display(auto2, "bad declaration"); auto1.setId(-3); display(auto1, "bad ID"); auto1.setId(2222); display(auto1, "good ID"); auto1.setMake("Toyota"); auto1.setModel("Corolla"); display(auto1, "chnage make and model"); auto2.setId(8686); auto2.setColor("blue"); auto2.setYear(2016); display(auto2, "change ID, color, and year"); auto2.setMpg(4); display(auto2, "bad mpg"); auto2.setMpg(30); display(auto2, "good mpg"); } public static void display(Automobile auto, String msg) { System.out.println(msg + " " + auto.getId() + " " + auto.getMake() + " " + auto.getModel() + " " + auto.getColor() + " " + auto.getYear() + " " + auto.getMpg() + " miles per gallon"); } }
  7. Create a class named Apartment that holds an apartment number, number of bedrooms, number of baths, and rent amount. Create a constructor that accepts values for each data field. Also create a get method for each field. Write an application that creates at least five Apartment objects. Then prompt a user to enter a minimum number of bedrooms required, a minimum number of baths required, and a maximum rent the user is willing to pay. Display data for all the Apartment objects that meet the user’s criteria or an appropriate message if no such apartments are available. Save the files as Apartment.java and TestApartments.java.

    public class Apartment { int aptNumber; int bedrooms; double baths; double rent; public Apartment(int num, int bdrms, double bths, double rent) { aptNumber = num; bedrooms = bdrms; baths = bths; this.rent = rent; } public int getAptNumber() { return aptNumber; } public int getBedrooms() { return bedrooms; } public double getBaths() { return baths; } public double getRent() { return rent; } }
    import java.util.*; public class TestApartments { public static void main (String args[]) { Scanner input = new Scanner(System.in); Apartment apt1 = new Apartment(101, 2, 1, 725); Apartment apt2 = new Apartment(102, 2, 1.5, 775); Apartment apt3 = new Apartment(103, 3, 2, 870); Apartment apt4 = new Apartment(104, 3, 2.5, 960); Apartment apt5 = new Apartment(105, 3, 3, 1100); int bdrms; int baths; double rent; int count = 0; System.out.print("Enter minimum number of bedrooms needed >> "); bdrms = input.nextInt(); System.out.print("Enter minimum number of bathrooms needed >> "); baths = input.nextInt(); System.out.print("Enter maximum rent willing to pay >> "); rent = input.nextDouble(); System.out.println("\nApartments meeting citeria of\nat least " + bdrms + " bedrooms, at least " + baths + " baths, and " + " no more than $" + rent + " rent:"); if(checkApt(apt1, bdrms, baths, rent)) { display(apt1); count = count + 1; } if(checkApt(apt2, bdrms, baths, rent)) { display(apt2); count = count + 1; } if(checkApt(apt3, bdrms, baths, rent)) { display(apt3); count = count + 1; } if(checkApt(apt4, bdrms, baths, rent)) { display(apt4); count = count + 1; } if(checkApt(apt5, bdrms, baths, rent)) { display(apt5); count = count + 1; } if(count == 0) System.out.println(" No aprtments met your critria."); } public static boolean checkApt(Apartment apt, int bdrms, double baths, double rent) { boolean result = false; if(apt.getBedrooms() >= bdrms && apt.getBaths() >= baths && apt.getRent() <= rent) result = true; return result; } public static void display(Apartment apt) { System.out.println(" Apt #" + apt.getAptNumber() + " " + apt.getBedrooms() + " bedrooms, and " + apt.getBaths() + " baths. Rent $" + apt.getRent()); } }
  8. Use the web to locate the lyrics to the traditional song “The Twelve Days of Christmas.” The song contains a list of gifts received for the holiday. The list is cumulative so that as each “day” passes, a new verse contains all the words of the previous verse, plus a new item. Write an application that displays the words to the song starting with any day the user enters. (Hint: Use a switch statement with cases in descending day order and without any break statements so that the lyrics for any day repeat all the lyrics for previous days.) Save the file as TwelveDays.java.

    import javax.swing.*; public class TwelveDays { public static void main (String args[]) { int choice; String entry; double total = 0; double price; choice = getChoice(); String suffix; if(choice >= 4) suffix = "th"; else if(choice == 3) suffix = "rd"; else if(choice == 2) suffix = "nd"; else suffix = "st"; System.out.println("\nOn the " + choice + suffix + " day of Christmas\n" + "My true love gave to me"); switch(choice) { case 12: System.out.println("Twelve drummers drumming"); case 11: System.out.println("Eleven pipers piping"); case 10: System.out.println("Ten lords a-leaping"); case 9: System.out.println("Nine ladies dancing"); case 8: System.out.println("Eight maids a-milking"); case 7: System.out.println("Seven swans a-swimming"); case 6: System.out.println("Six geese a-laying"); case 5: System.out.println("Five golden rings"); case 4: System.out.println("Four calling birds"); case 3: System.out.println("Three French hens"); case 2: System.out.println("Two turtle doves and"); case 1: System.out.println("A partridge in a pear tree"); break; default: System.out.println("Invalid choice"); } } public static int getChoice() { int choice; String entry; entry = JOptionPane.showInputDialog(null, "From what day do you\n" + "want to start the song\n" + "The Twelve Days of Christmas?"); choice = Integer.parseInt(entry); return choice; } }