Starting Out With Java - Programming Projects

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

10. Largest and Smallest Write a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered. The value -99 is not to be counted as part of the series.

import java.util.Scanner; class LargestAndSmallest { public static void main(String[] args) { int Largest; int Smallest; int num; Scanner scan = new Scanner(System.in); System.out.print("Enter an integer (-99 to stop):"); num = scan.nextInt(); Largest = Smallest = num; if(num!=-99) { while(num!=-99) { if(num>Largest) Largest = num; if(num<Smallest) Smallest = num; System.out.print(" Enter an integer (-99 to stop):"); num = scan.nextInt(); } System.out.println(" The smallest number was:"+Smallest); System.out.println("The largest number was: "+Largest); } } }

Design a class named Person with fields for holding a person's name, address, and telephone number (all as Strings). Write a constructor that initializes all of these values, and mutator and accessor methods for every field. Next, design a class named Customer, which inherits from the Person class. The Customer class should have a String field for the customer number and a boolean field indicating whether the customer wishes to be on a mailing list. Write a constructor that initializes these values and the appropriate mutator and accessor methods for the class's fields. Demonstrate the Customer class in a program that prompts the user to enter values for the customer's name, address, phone number, and customer number, and then asks the user whether or not the customer wants to recieve mail. Use this information to create a customer object and then print its information. Put all of your classes in the same file. To do this, do not declare them public. Instead, simply write: class Person { ... } class Customer { ... }

Unable to be found...

2.8: Cookie Calories A bag of cookies holds 40 cookies. The calorie information on the bag claims that there are 10 servings in the bag and that a serving equals 300 calories. Write a program that lets the user enter the number of cookies he or she actually ate and then reports the number of total calories consumed.

import java.util.Scanner; public class CookieCalorieCounter { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter number of cookies eaten: "); int n = in.nextInt(); System.out.println("Your calorie intake was: " + (75*n) + " calories."); } }

1. Area Class Write a class that has three overloaded static methods for calculating the areas of the following geometric shapes: - circles - rectangles - cylinders Here are the formulas for calculating the area of the shapes. Area of a circle: Area = π r2 where p is Math.PI and r is the circle's radius Area of a rectangle: Area = Width x Length Area of a cylinder: Area = π r2 h where p is Math.PI, r is the radius of the cylinder's base, and h is the cylinder's height Because the three methods are to be overloaded, they should each have the same name, but different parameter lists. Demonstrate the class in a complete program.

Copy from this link: https://docs.google.com/document/d/1rPLVdjOT0_Pm-N3bsRYX33aJsAdLAzTGX4G8vW2kamk/edit?usp=sharing

19. Squares. Write a program class named SquareDisplay that asks the user for a positive integer no greater than 15. The program should then display a square on the screen using the character 'X'. The number entered by the user will be the length of each side of the square. For example, if the user enters 5, the program should display the following: XXXXX XXXXX XXXXX XXXXX XXXXX INPUT and PROMPTS. The program prompts for an integer as follows: "Enter an integer in the range of 1-15: ". OUTPUT. The output should be a square of X characters as described above. CLASS NAMES. Your program class should be called SquareDisplay

import java.util.Scanner; //Class declaration public class SquareDisplay { // Main function public static void main(String[] args) { // Scanner object to get the input Scanner sc = new Scanner(System.in); // flag which will set true on valid input boolean done = false; // loop till a valid input is obtained while (!done) { try { // try catch to check if only number is inserted. System.out.print("Enter an integer in the range of 1-15: "); int index = Integer.parseInt(sc.next()); if (index < 1 || index > 15) { // checking if input is in valid range System.out.println("Please enter number between 1 and 15 only."); } else { //printing the square for (int i = 0; i < index; i++) { for (int j = 0; j < index; j++) { System.out.print("X"); } System.out.println(); } done = true; sc.close(); } } catch (NumberFormatException e) { System.out.println("Please enter a valid number."); } } } }

Write an exception class named InvalidTestScore. Modify the TestScores class you wrote in Exercise 1 so that it throws an InvalidTestScore exception if any of the test scores in the array are invalid. Test your exception in a program (in a Driver class located in the same file). Your program should prompt the user to enter the number of test scores, and then ask for each test score individually. Then, it should print the average of the test scores. If the average method throws an InvalidTestScore exception, the main method should catch it and print "Invalid test score."

import java.util.Scanner; class InvalidTestScore extends Exception{ public InvalidTestScore(){ super(); } } class TestScores { private int[] scores; public TestScores(int[] scores){ this.scores = scores; } public double average() throws InvalidTestScore{ double sum = 0; for(int i=0; i<scores.length; i++){ if(scores[i] > 100 || scores[i] < 0){ throw new InvalidTestScore(); }else{ sum += scores[i]; } } return sum/scores.length; } } class Driver { public static void main(String args[]) throws InvalidTestScore{ Scanner scanner = new Scanner(System.in); System.out.print("Enter number of test scores:"); int length = scanner.nextInt(); int[] scores = new int[length]; for(int i=0; i<length; i++){ System.out.print("Enter test score " + (i+1) + ":"); scores[i] = scanner.nextInt(); } TestScores test = new TestScores(scores); try{ System.out.print(test.average()); }catch (InvalidTestScore i){ System.out.print("Invalid test score."); } } }

2.14: Male and Female Percentages Write a program that asks the user for the number of males and the number of females registered in a class. The program should display the percentage of males and females in the class. Hint: Suppose there are 8 males and 12 females in a class. There are 20 students in the class. The percentage of males can be calculated as: (8/20) * 100, or 40%. The percentage of females can be calculated as: (12/20) * 100, or 60%.

//ClassGenderPercentages.java import java.util.Scanner; //class declaration public class ClassGenderPercentages { //main method public static void main(String[] args) { //declare variables int males, females; double malePercentage = 0, femalePercentage = 0; //create a scanner object for a scanner class Scanner input=new Scanner(System.in); System.out.print("Enter number of males registered: "); males=input.nextInt(); //Get number of females registered from user System.out.print("Enter number of females registered: "); females=input.nextInt(); try{ malePercentage = (males*100/(males+females)); ; femalePercentage = (females*100/(males+females)); }catch(Exception e){ e.printStackTrace(); } // Display statements for the percentages of male and female System.out.print("The percentage of males registered is: "+malePercentage+"%" ); System.out.print("\n"+"The percentage of females registered is: "+femalePercentage+"%"); } }

Write a class that has three overloaded static methods for calculating the areas of the following geometric shapes: • circles -- area = π*radius^2 (format the answer to have two decimal places) • rectangles -- area = width * length • trapezoid -- area = (base1 + base2) * height/2 Because the three methods are to be overloaded, they should each have the same name, but different parameters (for example, the method to be used with circles should only take one parameter, the radius of the circle). Demonstrate the methods in a program that prints out the following areas, each on a separate line: • the area of a circle with radius 3 • the area of a rectangle with length 2 and width 4 • the area of a trapezoid with base lengths 3 and 5 and height 5

Copy the answer from this link: https://docs.google.com/document/d/14rTIfoNyckms8wKiOGNsbbGPXizNrGu6qWGqH1V2bBI/edit?usp=sharing

Write a class named Car that has the following fields: • yearModel: The yearModel field is an int that holds the car's year model. • make: The make field is a String object that holds the make of the car. • speed: The speed field is an int that holds the car's current speed. In addition, the class should have the following methods: • Constructor: The constructor should accept the car's year model and make as arguments. These values should be assigned to the object's yearModel and make fields. The constructor should also assign 0 to the speed field. • Accessor: The appropriate accessor methods should be implemented to access the values stored in the object's yearModel, make, and speed fields. • accelerate: The accelerate method should add 5 to the speed field when it is called. • brake: The brake method should subtract 5 from the speed field each time it is called. Demonstrate the class in a program that contains a Car object, and then calls the accelerate method five times. After each call to the accelerate method, get the current speed of the car and print it on a separate line. Then, call the brake method five times, each time printing the current speed of the car on a separate line.

public class Car { private int yearModel; private String make; private int speed; public Car(int yearModel, String make) { this.yearModel = yearModel; this.make = make; speed = 0; } public int getYearModel() { return yearModel; } public String getMake() { return make; } public int getSpeed() { return speed; } public void accelerate() { speed += 5; } public void brake() { if (speed > 0) speed -= 5; } public static void main(String[] args) { Car myCar = new Car(2010, "Honda"); // accelerate 5 times for(int count = 1; count<=5; count++){ myCar.accelerate(); System.out.println(myCar.getSpeed()); } // brake 5 times for(int count = 1; count<=5; count++){ myCar.brake(); System.out.println(myCar.getSpeed()); } } }

Write a class named Employee that has the following fields: • name: The name field is a String object that holds the employee's name. • idNumber: The idNumber is an int variable that holds the employee's ID number. • department: The department field is a String object that holds the name of the department where the employee works. • position: the position field is a string object that holds the employee's job title. Write appropriate mutator methods that store the values in these fields and accessor methods that return the values in these fields. Once you have written the class, add a main method that creates three Employee objects to hold the following data: Name ID Number Department Position Susan Meyers 47899 Marketing Sales Rep Mark Jones 39119 IT Programmer Joy Rogers 81774 Manufacturing Engineer The program should store this data in the three objects and then display the data for each employee in the format: Name, employee number ID Number, works as a Position in Department. For example: Susan Meyers, employee 47899, works as a Sales Rep in Marketing. Print each statement on a separate line in the order Susan, Mark, Joy.

public class Employee { //naming instance fields private String name; private int idNumber; private String department; private String position; //set instance mutators methods - no static public void setName( String listName ) { name = listName; } public void setIdNumber( int listIdNumber ) { idNumber = listIdNumber; } public void setIdNumber( String listIdNumber ) { idNumber = Integer.parseInt(listIdNumber); } public void setDepartment( String listDepartment) { department = listDepartment; } public void setPosition( String listPosition) { position = listPosition; } //set accessors public String getName() { return name; } public String getDepartment() { return department; } public int getIdNumber() { return idNumber; } public String getPosition () { return position; } //constructors public Employee( String emplName, int emplIdNumber, String emplDepartment, String emplPosition ) { name = emplName; idNumber = emplIdNumber; department = emplDepartment; position = emplPosition; } public Employee() { name = ""; idNumber = 0; department = ""; position = ""; } public static void main(String[] args) { Employee employee1 = new Employee("Susan Meyers", 47899, "Marketing", "Sales Rep"); Employee employee2 = new Employee("Mark Jones", 39119, "IT", "Programmer"); Employee employee3 = new Employee("Joy Rogers", 81774, "Manufacturing", "Engineer"); System.out.println( employee1.getName() + ", employee number " + employee1.getIdNumber() + ", works as a " + employee1.getPosition() + " in " + employee1.getDepartment() + "."); System.out.println( employee2.getName() + ", employee number " + employee2.getIdNumber() + ", works as a " + employee2.getPosition() + " in " + employee2.getDepartment() + "."); System.out.println( employee3.getName() + ", employee number " + employee3.getIdNumber() + ", works as a " + employee3.getPosition() + " in " + employee3.getDepartment() + "."); } }

In a program, write a method that accepts two arguments: an array of integers and a number n. The method should print all of the numbers in the array that are greater than the number n (in the order that they appear in the array, each on their own line). In the same file, create a main method and call your function using the following data sets: The array {1, 5, 10, 2, 4, -3, 6} and the number 3. The array {10, 12, 15, 24} and the number 12.

public class LargerThanN { public static int[] greaterNum(int[] intArray, int number) { int[] greaterNumRtnd = new int[intArray.length]; int greaterNumRtndIndex = 0; for(int index = 0; index < intArray.length; index++) { if(intArray[index] > number) { greaterNumRtnd[greaterNumRtndIndex] = intArray[index]; greaterNumRtndIndex += 1; } } return greaterNumRtnd; } public static void main(String[] args) { int[] intArray1 = {1, 5, 10, 2, 4, -3, 6}; int number1 = 3; int[] greaterNumbersRtnd1 = greaterNum(intArray1, number1); int[] intArray2 = {10, 12, 15, 24}; int number2 = 12; int[] greaterNumbersRtnd2 = greaterNum(intArray2, number2); for(int index = 0; index < greaterNumbersRtnd1.length; index++) { if(greaterNumbersRtnd1[index] != 0) { System.out.println(greaterNumbersRtnd1[index]); } } for(int index = 0; index < greaterNumbersRtnd2.length; index++) { if(greaterNumbersRtnd2[index] != 0) { System.out.println(greaterNumbersRtnd2[index]); } } } }

Write a class named TestScores. The class constructor should accept an array of test scores as its argument. The class should have a method that returns the average of the test scores. If any test score in the array is negative or greater than 100, the class should throw an IllegalArgumentException. Demonstrate the class in a program (create a Driver class in the same file). The program should ask the user to input the number of test scores to be counted, and then each individual test score. It should then make an array of those scores, create a TestScore object, and print the average of the scores. If an IllegalArgumentException is thrown, the main method should catch it, print "Test scores must have a value less than 100 and greater than 0." and terminate the program.

Unable to be found...

2.4: Star Pattern Write a program that displays the following pattern: * *** ***** ******* ***** *** * Output. Seven lines of output as follows: The first consists of 3 spaces followed by a star. The second line consists of 2 spaces followed by a 3 stars. The third consists of one space followed by 5 stars, and the fourth consists just of 7 stars. The fifth line is identical to third, th sixth to the second and the seventh to the first. CLASS NAMES. Your program class should be called StarPattern

class StarPattern { public static void main (String[] args) { int x = 1; int increment_by = 2; while (x > 0) { // print spaces int spaces = 4 - x / 2; for (int i = 1; i <= spaces; i++) System.out.print(" "); // print asterisks for (int i = 1; i <= x; i++) System.out.print("*"); // end line System.out.println(); // change width if (x == 7) increment_by = -2; // reverse x += increment_by; } } }

2.19: Word Game Write a program that plays a word game with the user. The program should ask the user to enter the following: His or her name His or her age The name of a city The name of a college A profession A type of animal A pet's name After the user has entered these items, the program should display the following story, inserting the user's input into the appropriate locations: There once was a person named NAME who lived in CITY. At the age of AGE, NAME went to college at COLLEGE. NAME graduated and went to work as a PROFESSION. Then, NAME adopted a(n) ANIMAL named PETNAME They both lived happily ever after! Prompts And Output Labels: There are no labels here but the prompts should simply be (respectively) "Enter your name: ", "Enter your age: ", "Enter the name of a city: ", "Enter the name of a college: ", "Enter profession: ", "Enter a type of animal: ", "Enter a pet name: ". Note that each prompt ends with a ":" followed by one space and is displayed so that the response will appear on the same line as the prompt itself. Input: Keep in mind that the input responses to the prompts may consist of multiple words. For example, name might be "John Jinkleheimer Schmidt". CLASS NAMES. Your program class should be called WordGame

//WordGame.java import java.util.Scanner; public class WordGame { public static void main(String[] args) { //declaration of variables String name; int age; String city; String college; String profession; String animal; String petName; //Create an instance of Scanner class Scanner scanner=new Scanner(System.in); System.out.println("Enter your name :"); //prompt for name name=scanner.nextLine(); System.out.println("Enter your age:"); //prompt for age age=Integer.parseInt(scanner.nextLine()); System.out.println("Enter the name of a city: "); //prompt for city city=scanner.nextLine(); System.out.println("Enter the name of a college: "); //prompt for college college=scanner.nextLine(); System.out.println("Enter profession: "); //prompt for profession profession=scanner.nextLine(); System.out.println("Enter a type of animal: "); //prompt for animal animal=scanner.nextLine(); System.out.println("Enter a pet name : "); //prompt for petName petName=scanner.nextLine(); //print a story to console System.out.println("There once was a person named"+name+" who lived in "+city+"."); System.out.println("At the age of "+age+","+name+" went to college at "+college+"."); System.out.println(name+" graduated and went to work as a"+profession+"."); System.out.println("Then, "+name+" adopted a(n) "+animal+" named "+petName); System.out.println("They both lived happily ever after!"); } }//end of the class

6. File Letter Counter Write a program that asks the user to enter the name of a file, and then asks the user to enter a character. The program should count and display the number of times that the specified character appears in the file. Use Notepad or another text editor to create a sample file that can be used to test the program.

import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.MessageFormat; import java.util.Scanner; public class FileLetterCounter { public FileLetterCounter() { display(); } public int getCharacterCount(File file, char _char) { int count = 0; try { FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); while(bufferedReader.ready()) { String line = bufferedReader.readLine(); for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == _char) count++; } } bufferedReader.close(); fileReader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return count; } public void display() { Scanner in = new Scanner(System.in); System.out.print("Enter file name: "); String fileName = in.nextLine(); File file = new File(fileName); System.out.print("Enter character to count: "); char parseChar = in.next().charAt(0); System.out.print( MessageFormat.format("The character ''{0}'' appears in the file {2} {1} times.", parseChar, getCharacterCount(file, parseChar), file.getName()) ); } public static void main(String[] args) { new FileLetterCounter(); } }

3.12:The Speed of Sound The speed of sound depends on the material the sound is passing through. Below is the approximate speed of sound (in feet per second) for air, water and steel: air: 1,100 feet per second water: 4,900 feet per second steel: 16,400 feet per second Write a program class TheSpeedOfSound that asks the user to enter "air", "water", or "steel", and the distance that a sound wave will travel in the medium. The program should then display the amount of time it will take. You can calculate the amount of time it takes sound to travel in air with the following formula: time = distance/1,100 You can calculate the amount of time it takes sound to travel in watert with the following formula: time = distance/4,900 You can calculate the amount of time it takes sound to travel in steel with the following formula: time = distance/16,400 Prompts And Output. The program prompts for the medium with: "Enter one of the following: air, water, or steel: " and reads the medium. If the medium is not air, water or steel the program prints the message: "Sorry, you must enter air, water, or steel." an nothing else. Otherwise the program prompts for the distance with ("Enter the distance the sound wave will travel: " and reads it in and then prints "It will take x seconds." where x is the time calculated by your program.

import java.io.BufferedReader; import java.io.InputStreamReader; public class TheSpeedOfSound { public static void main(String[] s) { String medium; double distance; double time; try{ BufferedReader choice = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter one of the following: air, water, or steel: "); medium = choice.readLine(); // reading input i.e. air, water or steel //check for air water and steel if (medium.equalsIgnoreCase("air") || medium.equalsIgnoreCase("water") || medium.equalsIgnoreCase("steel")){ System.out.println("Enter the distance the sound wave will travel: "); distance = Double.parseDouble(choice.readLine()); // read distance value if it is air water or steel switch (medium) { //if medium is air case "air": time = distance/1100; System.out.print("It will take " + time + " seconds."); break; //if medium is water case "water": time = distance/4900; System.out.print("It will take " + time + " seconds."); break; //if medium is steel case "steel": time = distance/16400; System.out.print("It will take " + time + " seconds."); break; } } else{ System.out.print("Sorry, you must enter air, water, or steel."); } } catch(Exception e){ e.printStackTrace(); } } }

A retail store has a preferred customer plan where customers can earn discounts on all their purchases. The amount of a customer's discount is determined by the amount of the customer's cumulative purchases in the store, as follows: When a preferred customer spends $500, they get a 5% discount on all future purchases. When a preferred customer spends $1,000, they get a 6% discount on all future purchases. When a preferred customer spends $1,5000, they get a 7% discount on all future purchases. When a preferred customer spends $2,000, they get a 10% discount on all future purchases. Design a class named PreferredCustomer, which inherits from the Customer class you created in Exercise 7. The preferredCustomer class should have int fields for the amount of the customer's purchases and the customer's discount level. Write a constructor that initializes these fields as well as accessor and mutator methods. Desmonstrate the class in a program that prompts the user to input the customer's name, address, phone number, customer number, whether they want to recieve mail, and the amount they've spent, and then uses that information to create a PreferredCustomer object and print its information. (Use string formatting to print the amount spent.) Create all of the classes in the same file by not delcaring any of them public.

import java.util.Scanner; class Person{ private String name; private String address; private String number; //Constructors public Person(String name, String address, String number){ this.name = name; this.address = address; this.number = number; } public Person(){} //Accessors public String getName(){ return this.name; } public String getAddress(){ return this.address; } public String getNumber(){ return this.number; } //Mutators public void setName(String n){ this.name = n; } public void setAddress(String a){ this.address = a; } public void setNumber(String n){ this.number = n; } } class Customer extends Person{ private String customerNumber; private boolean recieveMail; //Constructors public Customer(String name, String address, String number, String customerN, boolean rm) { super(name, address, number); this.customerNumber = customerN; this.recieveMail = rm; } public Customer(){} //Accessors public String getCustomerNumber(){ return this.customerNumber; } public boolean getRecieveMail(){ return this.recieveMail; } //Mutators public void setCustomerNumber(String c){ this.customerNumber = c; } public void setRecieveMail(boolean r){ this.recieveMail = r; } } class PreferredCustomer extends Customer{ private int amtPurchased; private int discountLevel = 0; public PreferredCustomer(String name, String address, String number, String customerN, boolean rm, int amtPurchased){ super(name, address, number, customerN, rm); this.amtPurchased = amtPurchased; if(amtPurchased >= 500 && amtPurchased < 1000){ this.discountLevel = 5; }else if(amtPurchased >= 1000 && amtPurchased < 1500){ this.discountLevel = 6; }else if(amtPurchased >= 1500 && amtPurchased < 2000){ this.discountLevel = 7; }else if(amtPurchased >= 2000){ this.discountLevel = 10; } } //Accessors public int getAmtPurchased(){ return this.amtPurchased; } public int getDiscountLevel(){ return this.discountLevel; } //Mutators public void setAmtPurchase(int amount){ this.amtPurchased = amount; } public void setDiscountLevel(){ if(amtPurchased >= 500 && amtPurchased < 1000){ this.discountLevel = 5; }else if(amtPurchased >= 1000 && amtPurchased < 1500){ this.discountLevel = 6; }else if(amtPurchased >= 1500 && amtPurchased < 2000){ this.discountLevel = 7; }else if(amtPurchased >= 2000){ this.discountLevel = 10; } } } class Driver { public static void main(String args[]){ Scanner scanner = new Scanner(System.in); System.out.print("Enter name of customer:"); String name1 = scanner.nextLine(); System.out.print("Enter address of customer:"); String address1 = scanner.nextLine(); System.out.print("Enter phone number of customer:"); String number1 = scanner.nextLine(); System.out.print("Enter customer number:"); String customerNumber = scanner.nextLine(); System.out.print("Enter yes/no -- does the customer want to recieve mail?:"); String answer = scanner.nextLine(); boolean recieveMail = (answer.equals("yes")); System.out.print("Enter amount customer has spent:"); int amtPurchased = Integer.parseInt(scanner.nextLine()); PreferredCustomer customer = new PreferredCustomer(name1, address1, number1, customerNumber, recieveMail, amtPurchased); System.out.println("\nCustomer: "); System.out.println("Name: "+customer.getName()); System.out.println("Address: "+customer.getAddress()); System.out.println("Phone Number: "+customer.getNumber()); System.out.println("Customer Number: "+customer.getCustomerNumber()); System.out.println("Recieve Mail?: "+customer.getRecieveMail()); System.out.printf("Amount Purchased: $%.2f\n",(float)customer.getAmtPurchased()); System.out.println("Percent off: " + customer.getDiscountLevel() + "%"); } }

3.8: Software Sales A software company sells a package that retails for $99. Quantity discounts are given according to the following table: Quantity Discount 10-19 20% 20-49 30% 50-99 40% 100 or more 50% Write a program that asks the user to enter the number of packages purchased. The program should then display the amount of the discount (if any) and the total amount of the purchase after the discount. For instance, to calculate 20% of a value N, you can use the formula: (20 / 100.0) * N (or 0.2 * N).

import java.util.Scanner; class SoftwareSales { public static void main(String[] args) { String userInput; String userOutput; double packagePrice=99; int userNumberOfPackages; double discount; double subTotal; double total; Scanner keyboard = new Scanner(System.in); System.out.print("Enter number of packages purchased:"); userNumberOfPackages = keyboard.nextInt(); if(userNumberOfPackages<10) { subTotal=packagePrice*userNumberOfPackages; discount=0; total=subTotal-discount; } else if(userNumberOfPackages<20) { subTotal=packagePrice*userNumberOfPackages; discount=((double)20/100)*subTotal; total=subTotal-discount; } else if(userNumberOfPackages<50) { subTotal=packagePrice*userNumberOfPackages; discount=((double)30/100)*subTotal; total=subTotal-discount; } else if(userNumberOfPackages<100) { subTotal=packagePrice*userNumberOfPackages; discount=((double)40/100)*subTotal; total=subTotal-discount; } else { subTotal=packagePrice*userNumberOfPackages; discount=((double)50/100)*subTotal; total=subTotal-discount; } userOutput=String.format(" Your discount is: $%.2f\nYour total is: $%.2f\n", discount, total); System.out.print(userOutput); } }

4.9: Population Write a program that will predict the size of a population of organisms. The program should ask the user for the starting number of organisms, their average daily population increase (as a percentage, expressed as a fraction in decimal form: for example 0.052 would mean a 5.2% increase each day), and the number of days they will multiply. A loop should display the size of the population for each day. Prompts, Output Labels and Messages.The three input data should be prompted for with the following prompts: "Enter the starting number organisms: ", "Enter the daily increase: ", and "Enter the number of days the organisms will multiply: " respectively. After the input has been read in successfully, a table is produced, for example: ----------------------------- 2 300.0 4 675.0 Under the heading is a line of 29 dashes followed by one line for each day, showing the day number and the population at the beginning of that day. Input Validation.Do not accept a number less than 2 for the starting size of the population. If the user fails to satisfy this print a line with this message "Invalid. Must be at least 2. Re-enter: " and try to read the value. Similarly, do not accept a negative number for average daily population increase, using the message "Invalid. Enter a non-negative number: " and retrying. Finally, do not accept a number less than 1 for the number of days they will multiply and use the message "Invalid. Enter 1 or more: ".

import java.util.Scanner; import java.text.DecimalFormat; public class Population { public static void main(String[] args) { double number_organisms = 0; //changed float into double double daily_increase = 0; //changed float into double int number_days = 0; Scanner input = new Scanner(System.in); System.out.print("Enter the starting number organisms: "); number_organisms = input.nextInt(); if (number_organisms < 2){ System.out.print("Invalid. Must be at least 2. Re-enter: "); number_organisms = input.nextInt(); } System.out.print("Enter the daily increase: "); daily_increase = input.nextDouble(); //changed Float into Double if (daily_increase <0){ System.out.print("Invalid. Enter a non-negative number:"); daily_increase = input.nextDouble(); //changed Float into Double } System.out.print("Enter the number of days the organisms will multiply: "); number_days = input.nextInt(); if (number_days < 1){ System.out.print("Invalid. Enter 1 or more: "); number_days = input.nextInt(); } System.out.print("Day\t\tOrganisms\n"); System.out.print("-----------------------------\n"); System.out.println("1\t\t" + (number_organisms)); for (int count = 2; count <= number_days; count++){ number_organisms = ((daily_increase * number_organisms) + number_organisms); System.out.print((count) + "\t\t" + (number_organisms) + "\n"); } } }

2. Distance Traveled The distance a vehicle travels can be calculated as follows: Distance = Speed * Time For example, if a train travels 40 miles-per-hour for three hours, the distance traveled is 120 miles. Write a program that asks for the speed of a vehicle (in miles-per-hour) and the number of hours it has traveled. Both values are assumed to be integers. It should use a loop to display the distance a vehicle has traveled for each hour of a time period specified by the user. For example, if a vehicle is traveling at 40 mph for a three-hour time period, it should display a report similar to the one that follows: Hours Distance Traveled --------------------------- 1 40 2 80 3 120 Input Validation: Do not accept a negative number for speed and do not accept any value less than 1 for time traveled.

import java.util.Scanner; public class DistanceTravelled { public static void main(String[] args) { Scanner piglet = new Scanner(System.in); int speed = -1; int distance; int time = 0; while (speed < 0) { System.out.print("Enter vehicle speed (in mph): "); speed = piglet.nextInt(); } while (time < 1) { System.out.print("Enter time travelled (in hrs): "); time = piglet.nextInt(); } System.out.println("Hour" + "\t" + "Distance Travelled"); System.out.println("--------------------------"); for (int x=1; x<=time; x++) { distance = speed *x; System.out.print(x + "\t\t" + distance + "\n"); } } }

8. Grade Book A teacher has five students who have each taken four tests. The teacher uses the following grading scale to assign a letter grade to a student, based on the average of his or her four test scores: Test Score Letter Grade 90-100 A 80-89 B 70-79 C 60-69 D 0-59 F Write a class that uses a String array or an ArrayList object to hold the five students' names, an array of five characters to hold the five students' letter grades, and five arrays of four doubles each to hold each student's set of test scores. You may find using a single 5x4 multi-dimensional array easier to manage instead of a separate array for each set of test scores. The class should have methods that return a specific student's name, the average test score, and a letter grade based on the average. Although averages are often floating-point values, you should cast the average test score to an integer when comparing with the grading scale. This reduces the possibility of error. Demonstrate the class in a program that allows the user to enter each student's name and his or her four test scores. It should then display each student's average test score and letter grade. Input Validation: Do not accept test scores less than zero or greater than 100.

import java.util.Scanner; public class GradeBook { String[] studentNames; char[] letterGrades; double[][] testGrades; public GradeBook() { studentNames = new String[5]; letterGrades = new char[5]; testGrades = new double[5][4]; } public String getStudentName(int number) { if ((number >= 1) && (number <= 5)) return studentNames[number - 1]; return null; } public double getAvgTestScore(int number) { if ((number >= 1) && (number <= 5)) { int sum = 0; for (int i = 0; i < 4; i++) sum += testGrades[number - 1][i]; return (sum / 4.0); } return -1.0; } public char getLetterGrade(double avgScore) { int avg = (int) avgScore; if ((avg >= 90) && (avg <= 100)) return 'A'; else if ((avg >= 80) && (avg <= 89)) return 'B'; else if ((avg >= 70) && (avg <= 79)) return 'C'; else if ((avg >= 60) && (avg <= 69)) return 'D'; else return 'F'; } public static void main(String[] args) { GradeBook record = new GradeBook(); Scanner input = new Scanner(System.in); int score; for (int i = 1; i <= 5; i++) { System.out.printf("Enter student %d name: ", i); record.studentNames[i - 1] = input.nextLine(); for (int j = 1; j <= 4; j++) { while (true) { System.out.printf("Enter student %s's"+ " grade for test %d: ",record.studentNames[i - 1], j); score = input.nextInt(); input.nextLine(); if ((score >= 0) && (score <= 100)) { record.testGrades[i - 1][j - 1] = score; break; } System.out.printf("Score cannot be less than 0 or greater than 100! Please try again.%n"); } } } double avg; System.out.printf("%n=== Grade Book Data ===%n%n"); for (int i = 1; i <= 5; i++) { avg = record.getAvgTestScore(i); System.out.printf("Student name: %s%n" +"\tAverage test score: %.2f%n" + "\tLetter grade: %c%n= = = = =%n", record.getStudentName(i), avg, record.getLetterGrade(avg)); } } }

Make a LandTract class with the following fields: • length - an int containing the tract's length • width - an int containing the tract's width The class should also have the following methods: • area - returns an int representing the tract's area • equals - takes another LandTract object as a parameter and returns a boolean saying whether or not the two tracts have the same dimensions (This applies regardless of whether the dimensions match up. i.e., if the length of the first is the same as the width of the other and vice versa, that counts as having equal dimensions.) • toString - returns a String with details about the LandTract object in the format: LandTract object with length 30 and width 40 (If, for example, the LandTract object had a length of 30 and a width of 40.) Write a separate program that asks the user to enter the dimensions for the two tracts of land (in the order length of the first, width of the first, length of the second, width of the second). The program should print the output of two tracts' toString methods followed by a sentence stating whether or not the tracts have equal dimensions. (If the tracts have the same dimensions, print, "The two tracts have the same size." Otherwise, print, "The two tracts do not have the same size.") Print all three statements on separate lines.

import java.util.Scanner; public class LandTract { public int length, width, area; public LandTract(){ length = 0; width = 0; area= 0; } public LandTract(int length, int width) { this.length = length; this.width = width; } public void setArea (int area){ this.area = area; } // Area public static int area(int length, int width) { return length * width; } // Equals public boolean equals(LandTract lt) { boolean equals; if (length == (lt.length) && width == (lt.width) || length == (lt.width) && width == (lt.length)) equals = true; else equals = false; return equals; } // ToString public String toString() { String str = ("LandTract" + " with length " + length + ", width " + width + ", and area " + area); return str; } public static void main(String[] args) { int length1 = 0; int width1 = 0; int area1 = 0; int length2 = 0; int width2 = 0; int area2 = 0; Scanner keyboard = new Scanner(System.in); // first tract System.out.print("Enter length of first land tract:"); length1 = keyboard.nextInt(); System.out.print("Enter width of first land tract:"); width1 = keyboard.nextInt(); LandTract land1 = new LandTract(length1,width1); area1 = LandTract.area(length1,width1); land1.setArea(area1); // second tract System.out.print("Enter length of second land tract:"); length2 = keyboard.nextInt(); System.out.print("Enter width of second land tract:"); width2 = keyboard.nextInt(); LandTract land2 = new LandTract(length2,width2); area2 = LandTract.area(length2,width2); land2.setArea(area2); // display System.out.println(land1.toString()); System.out.println(land2.toString()); if (land1.equals(land2)) System.out.println("The two tracts have the same size."); else System.out.println("The two tracts do not have the same size."); } }

1. A showChar Method Write a method named showChar. The method should accept two arguments: a reference to a String object and an integer. The integer argument is a character position within the String, with the first character being at position 0. When the method executes, it should display the character at that character position. The method does not return anything. Here is an example of a call to the method: showChar("New York", 2); In this call, the method will display the character w because it is in position 2. Demonstrate the method in a complete program-- use the class name Method_showChar

import java.util.Scanner; public class Method_showChar { public static void showChar(String s, int index) { if(index < s.length()) { System.out.println(s.charAt(index)); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a line of text:"); String s = in.nextLine(); System.out.print(" Enter your index:"); int index = in.nextInt(); System.out.print(" "); showChar(s, index); } }

8. Parking Ticket Simulator For this assignment you will design a set of classes that work together to simulate a police officer issuing a parking ticket. You should design the following classes: - The ParkedCar Class: This class should simulate a parked car. The class's responsibili- ties are as follows: - To know the car's make, model, color, license number, and the number of minutes that the car has been parked. - The ParkingMeter Class: This class should simulate a parking meter. The class's only responsibility is as follows: - To know the number of minutes of parking time that has been purchased. - The ParkingTicket Class: This class should simulate a parking ticket. The class's responsibilities are as follows: - To report the make, model, color, and license number of the illegally parked car - To report the amount of the fine, which is $25 for the first hour or part of an hour that the car is illegally parked, plus $10 for every additional hour or part of an hour that the car is illegally parked - To report the name and badge number of the police officer issuing the ticket - The PoliceOfficer Class: This class should simulate a police officer inspecting parked cars. The class's responsibilities are as follows: - To know the police officer's name and badge number - To examine a ParkedCar object and a ParkingMeter object, and determine whether the car's time has expired - To issue a parking ticket (generate a ParkingTicket object) if the car's time has expired Write a program that demonstrates how these classes collaborate. Make the aforementioned classes nested classes within the class containing your main method; only this outermost class can be declared public.

import java.util.Scanner; public class ParkingTicketSimulator { static class ParkedCar { private String make, model, licenseNum, color; private int minsParked; public void setMake(String make) { this.make = make; return; } public void setModel(String model) { this.model = model; return; } public void setColor(String color) { this.color = color; return; } public void setLicenseNum(String licenseNum) { this.licenseNum = licenseNum; return; } public void setMinsParked(int minsParked) { this.minsParked = minsParked; return; } } static class ParkingMeter { private int minsPurchased; public void setMinsPurchased(int minsPurchased) { this.minsPurchased = minsPurchased; return; } } static class ParkingTicket { private int fineAmount; private String poName; private int poBadgeNum; private ParkedCar car; public ParkingTicket(ParkedCar car, int mins, String poName, int poBadgeNum) { this.car = car; this.poName = poName; this.poBadgeNum = poBadgeNum; if (mins <= 60) fineAmount = 25; else fineAmount = (25 + (10 * ((mins - 60) / 60))); } public String getCarMake() { return car.make; } public String getCarModel() { return car.model; } public String getCarColor() { return car.color; } public String getCarLicenseNum() { return car.licenseNum; } public int getFineAmount() { return fineAmount; } public String getPOName() { return poName; } public int getPOBadgeNum() { return poBadgeNum; } } static class PoliceOfficer { private String name; private int badgeNum; public void setPOName(String name) { this.name = name; return; } public void setPOBadgeNum(int badgeNum) { this.badgeNum = badgeNum; return; } public ParkingTicket checkCarAndMeter( ParkedCar car, ParkingMeter meter) { ParkingTicket ticket = null; int mins; if ((mins = (car.minsParked - meter.minsPurchased)) > 0) ticket = new ParkingTicket(car, mins, name, badgeNum); return ticket; } } public static void main(String[] args) { Scanner input = new Scanner(System.in); ParkedCar car = new ParkedCar(); ParkingMeter meter = new ParkingMeter(); PoliceOfficer po = new PoliceOfficer(); System.out.printf("=== Parking Ticket Simulator ===%n%n" + "---------%nCar Data%n---------%n%n" + "Enter car make: "); car.setMake(input.nextLine()); System.out.printf("Enter car model: "); car.setModel(input.nextLine()); System.out.printf("Enter car color: "); car.setColor(input.nextLine()); System.out.printf("Enter car license number: "); car.setLicenseNum(input.nextLine()); System.out.printf("Enter minutes car has been parked: "); car.setMinsParked(input.nextInt()); System.out.printf("%n----------%nMeter Data%n----------" + "%n%nEnter minutes purchased by driver: "); meter.setMinsPurchased(input.nextInt()); input.nextLine(); System.out.printf("%n-------%nPO Data%n-------%n%n" + "Enter police officer's name: "); po.setPOName(input.nextLine()); System.out.printf("Enter police officer's badge number: "); po.setPOBadgeNum(input.nextInt()); System.out.printf("%n---------------------%n" + "Parking Ticket Issued%n---------------------" + "%n%n"); ParkingTicket ticket; if ((ticket = po.checkCarAndMeter(car, meter)) != null) { System.out.printf("| Parking ticket #: . . .%n" + "| Fined amount: $%d.00%n" + "| Car issued to: %s %s %s, license #: %s%n" + "| Issued by officer: %s, badge #: %d%n", ticket.getFineAmount(), ticket.getCarColor(), ticket.getCarMake(), ticket.getCarModel(), ticket.getCarLicenseNum(), ticket.getPOName(), ticket.getPOBadgeNum()); } else { System.out.printf("No parking ticket has been issued!%n"); } return; } }

Design a Payroll class with the following fields: • name: a String containing the employee's name • idNumber: an int representing the employee's ID number • rate: a double containing the employee's hourly pay rate • hours: an int representing the number of hours this employee has worked The class should also have the following methods: • Constructor: takes the employee's name and ID number as arguments • Accessors: allow access to all of the fields of the Payroll class • Mutators: let the user assign values to the fields of the Payroll class • grossPay: returns the employee's gross pay, which is calculated as the number of hours worked times the hourly pay rate. Write another program that demonstrates the class by creating a Payroll object, then asking the user to enter the data for an employee in the order: name, ID number, rate, hours. The program should then print out a statement in the following format (for example, if you had an employee named Chris Jacobsen with ID number 11111, who works for 5 hours at $10/hr): Chris Jacobsen, employee number 11111, made $50.00 in gross pay. Using text forming so that the gross pay is rounded to two decimal places.

import java.util.Scanner; public class Payroll { public static void main(String[] args) { //Get values from user Scanner scanner = new Scanner(System.in); System.out.print("Enter employee's name:"); String name = scanner.nextLine(); System.out.print("Enter employee's ID number:"); int id = scanner.nextInt(); System.out.print("Enter hourly rate:"); double rate = scanner.nextDouble(); System.out.print("Enter number of hours worked:"); int hours = scanner.nextInt(); //Make Payroll object Payroll myPay = new Payroll(name, id); myPay.setRate(rate); myPay.setHours(hours); String grossPay = String.format("%.2f", myPay.grossPay()); System.out.println(myPay.getName() + ", employee number " + myPay.getID() + ", made $"+ grossPay + " in gross pay."); } private String name; private int idNumber; private double rate; private int hours; public Payroll(String name, int id){ this.name = name; this.idNumber = id; } //Accessors public String getName(){ return this.name; } public int getID(){ return this.idNumber; } public double getRate(){ return this.rate; } public int getHours(){ return this.hours; } //Mutators public void setName(String name){ this.name = name; } public void setID(int id){ this.idNumber = id; } public void setRate(double rate){ this.rate = rate; } public void setHours(int h){ this.hours = h; } //Methods public double grossPay(){ return this.rate*this.hours; } }

7. Quarterly Sales Statistics Write a program that lets the user enter four quarterly sales figures for six divisions of a company. The figures should be stored in a two-dimensional array. Once the figures are entered, the program should display the following data for each quarter: - A list of the sales figures by division - Each division's increase or decrease from the previous quarter (this will not be dis- played for the first quarter) - The total sales for the quarter - The company's increase or decrease from the previous quarter (this will not be dis- played for the first quarter) - The average sales for all divisions that quarter - The division with the highest sales for that quarter Input Validation: Do not accept negative numbers for sales figures.

import java.util.Scanner; public class QuarterlySalesStats { public static void dataEntry(int [][] companyFigures) { Scanner keyboard = new Scanner(System.in); for(int i = 0; i < companyFigures.length; i++){ for(int j = 0; j < companyFigures[0].length; j++) { System.out.print("Enter division " + (i+1) + "'s sales figure for quarter " + (j+1) + ": "); companyFigures[i][j] = keyboard.nextInt(); while(companyFigures[i][j] < 0){ System.out.println("Sales figure cannot be negative! Please try again."); System.out.print("Enter division " + (i+1) + "'s sales figure for quarter " + (j+1) + ": "); companyFigures[i][j] = keyboard.nextInt(); } } // end inner for } // end outer for } // end dataEntry public static void showFigures(int [][] companyFigures) { System.out.println("\n=== Quarterly Sales Figures ===\n"); System.out.println("-----------\nLISTING\n-----------"); int change; for(int i = 0; i < companyFigures.length; i++){ change = 0; System.out.println("\nDivision: " + (i+1) + "\n-----------"); for(int j = 0; j < companyFigures[0].length; j++) { if(j >= 1) { change = companyFigures[i][j] - companyFigures[i][j-1]; if (change >= 1) { System.out.println("Quarter " + (j+1) + ": " + companyFigures[i][j] + " (+" + change + ")"); } else { System.out.println("Quarter " + (j+1) + ": " + companyFigures[i][j] + " (" + change + ")"); } }else{ System.out.println("Quarter " + (j+1) + ": " + companyFigures[i][j]); } } // end inner for } // end outer for } // end showFigures public static void calcQuarterSales(int[][] companyFigures, int NUMQUARTERS, int NUMDIVISIONS) { int totalQuarterSales; int[] totalQuarterSalesArray = new int[NUMQUARTERS]; int change; System.out.println("\n-----------\nSTATS\n-----------\n"); for(int j = 0; j < companyFigures[0].length; j++){ totalQuarterSales = 0; for(int i = 0; i < companyFigures.length; i++) { totalQuarterSales += companyFigures[i][j]; } // end inner for change = 0; totalQuarterSalesArray[j] = totalQuarterSales; System.out.println("Quarter " + (j+1)); // Totals if(j >= 1) { change = totalQuarterSalesArray[j] - totalQuarterSalesArray[j-1]; if( change >= 1){ System.out.println("\t\tTotal: " + totalQuarterSalesArray[j] + " (+" + change + ")"); } else { System.out.println("\t\tTotal: " + totalQuarterSalesArray[j] + " (" + change + ")"); } } else { System.out.println("\t\tTotal: " + totalQuarterSalesArray[j]); } // Averages Double avg = (totalQuarterSalesArray[j] / (NUMDIVISIONS * 1.0)); avg = Math.round(avg*100.0)/100.0; System.out.printf("\t\tAverage: %.2f\n", avg); // Highest Sales int highestSale = 0; int highestDivision = 0; for(int i = 0; i < companyFigures.length; i++) { if(companyFigures[i][j] > highestSale) { highestSale = companyFigures[i][j]; highestDivision = i + 1; } } System.out.println("\t\tHighest sales: division " + highestDivision + " (" + highestSale + ")"); } // end outer for } public static void main(String[] args) { int NUMDIVISIONS = 6; int NUMQUARTERS = 4; int[][] companyFigures = new int[NUMDIVISIONS][NUMQUARTERS]; dataEntry(companyFigures); showFigures(companyFigures); calcQuarterSales(companyFigures, NUMQUARTERS, NUMDIVISIONS); } }

Write a RainFall class that has the following field: • an array of doubles that stores the rainfall for each of the 12 months of the year (where the first index corresponds with January, the second with February, etc.) The class should also have the following methods: • a method that returns the total rainfall for the entire year • a method that returns the average monthly rainfall for the year • a method that returns the month with the most rain as a string • a method that returns the month with the least rain as a string Demonstrate the class in a program that takes 12 doubles from the user (take the doubles in the order of the months of the year, the first corresponding to the rainfall in January, etc.). Do input validation: if the user inputs a negative number, ignore it and continue asking them for input until you have 12 nonnegative doubles. Once the user has given you all 12 doubles, create an instance of the RainFall class and call its methods, printing out the total rainfall, the average monthly rainfall, the month with the most rain, and the month with the least rain, each on a separate line.

import java.util.Scanner; public class RainFall { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double[] rainfall = new double[12]; int i = 0; System.out.print("Enter rainfall for month 1:"); while(i < 12){ double rain = scanner.nextDouble(); if(rain >= 0){ rainfall[i] = rain; i++; } if(i!=12){ System.out.print("Enter rainfall for month " + (i+1) + ":"); } } RainFall rf = new RainFall(rainfall); System.out.println(rf.total()); System.out.println(rf.average()); System.out.println(rf.most()); System.out.println(rf.least()); } private double[] rainfall = new double[12]; public RainFall(double[] rf){ this.rainfall = rf; } public double total(){ double sum = 0; for(int i=0; i<12; i++){ sum+=this.rainfall[i]; } return sum; } public double average(){ return this.total()/12.0; } public String most(){ double mostRain = this.rainfall[0]; int index = 0; for(int i=1; i<12; i++){ if(this.rainfall[i] > mostRain){ mostRain = this.rainfall[i]; index = i; } } return this.convertToMonth(index); } public String least(){ double leastRain = this.rainfall[0]; int index = 0; for(int i=1; i<12; i++){ if(this.rainfall[i] < leastRain){ leastRain = this.rainfall[i]; index = i; } } return this.convertToMonth(index); } private String convertToMonth(int index){ switch(index){ case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return ""; } } }

4.1: Roman Numerals Write a program that asks the user to enter a number within the range of 1 through 10. Use a switch statement to display the Roman numeral version of that number. Input Validation: Do not accept a number less than 1 or greater than 10. Prompts And Output Labels. Use the following prompt for input: "Enter a number in the range of 1 - 10: ". The output of the program should be just a Roman numeral, such as VII. CLASS NAMES. Your program class should be called RomanNumerals

import java.util.Scanner; public class RomanNumerals{ public static void main(String [] args){ Scanner keyboard = new Scanner (System.in); int number; System.out.println("Enter a number in the range of 1 - 10: "); number = keyboard.nextInt(); if(number < 1 || number > 10){ System.out.println("INVALID");} switch(number){ case 1: System.out.println("I"); break; case 2: System.out.println("II"); break; case 3: System.out.println("III"); break; case 4: System.out.println("IV"); break; case 5: System.out.println("V"); break; case 6: System.out.println("VI"); break; case 7: System.out.println("VII"); break; case 8: System.out.println("VIII"); break; case 9: System.out.println("IX"); break; case 10: System.out.println("X"); break; } } }

3.11: Running the Race Write a program that asks for the names of three runners and the time, in minutes, it took each of them to finish a race. The program should display the names of the runners in the order that they finished.

import java.util.Scanner; public class Runners { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); double t1, t2, t3; System.out.print("Enter runner 1 name:"); String name1; name1 = keyboard.nextLine(); System.out.print(" Enter runner 1 time (in minutes):"); String time1; time1 = keyboard.nextLine(); System.out.print(" Enter runner 2 name:"); String name2; name2 = keyboard.nextLine(); System.out.print(" Enter runner 2 time (in minutes):"); String time2; time2 = keyboard.nextLine(); System.out.print(" Enter runner 3 name:"); String name3; name3 = keyboard.nextLine(); System.out.print(" Enter runner 3 time (in minutes): "); String time3; time3 = keyboard.nextLine(); t1=Double.parseDouble(time1); t2=Double.parseDouble(time2); t3=Double.parseDouble(time3); if(t1>t2 && t1>t3) { if(t2>t3) { System.out.print("" + name3 + "\n" + name2 + "\n" + name1 + "\n"); } else { System.out.print("" + name2 + "\n" + name3 + "\n" + name1 + "\n"); } } else if(t2>t1 && t2>t3) { if(t1>t3){ System.out.print("" + name3 + "\n" + name1 + "\n" + name2 + "\n"); } else { System.out.print("" + name1 + "\n" + name3 + "\n" + name2 + "\n"); } } else if(t3>t2 && t3>t1) { if(t2>t1){ System.out.print("" + name1 + "\n" + name2 + "\n" + name3 + "\n"); } else { System.out.print("" + name2 + "\n" + name1 + "\n" + name3 + "\n"); } } else if(t3==t2||t3==t1) { if(t2>t1){ System.out.print(""+ name1 + "\n" + name2 + "\n" + name3 + "\n"); } else { System.out.print("" + name1 + "\n" + name2 + "\n" + name3 + "\n"); } } } }

Write a Temperature class that will hold a temperature in Fahrenheit and provide methods to get the temperature in Fahrenheit, Celsius, and Kelvin. The class should have the following field: • ftemp: a double that holds a Fahrenheit temperature. The class should have the following methods: • Constructor: The constructor accepts a Fahrenheit temperature (as a double) and stores it in the ftemp field. • setFahrenheit: The set Fahrenheit method accepts a Fahrenheit temperature (as a double) and stores it in the ftemp field. • getFahrenheit: Returns the value of the ftemp field as a Fahrenheit temperature (no conversion required) • getCelsius: Returns the value of the ftemp field converted to Celsius. Use the following formula to convert to Celsius: Celsius = (5/9) * (Fahrenheit - 32) • getKelvin: Returns the value of the ftemp field converted to Kelvin. Use the following formula to convert to Kelvin: Kelvin = ((5/9) * (Fahrenheit - 32)) + 273 Demonstrate the Temperature class by writing a separate program that asks the user for a Fahrenheit temperature. The program should create an instance of the Temperature class, with the value entered by the user passed to the constructor. The program should then call the object's methods to display the temperature in the following format (for example, if the temperature in Fahrenheit was -40): The temperature in Fahrenheit is -40.0 The temperature in Celsius is -40.0 The temperature in Kelvin is 233.0

import java.util.Scanner; public class Temperature { double ftemp; Temperature(double ftemp) { this.ftemp = ftemp; } public void setFahrenheit(double ftemp) { this.ftemp = ftemp; } double getFahrenheit() { return ftemp; } double getCelsius() { return ((double)5/9*(ftemp-32)); } double getKelvin() { return (((double)5/9*(ftemp-32))+273); } public static void main(String[] args) { double ftemp; // Holds temp in Fahrenheit Scanner input = new Scanner(System.in); System.out.print("Enter a Fahrenheit temperature:"); ftemp = input.nextDouble(); Temperature temp = new Temperature(ftemp); temp.setFahrenheit(ftemp); System.out.println("The temperature in Fahrenheit is " + temp.getFahrenheit()); System.out.println("The temperature in Celsius is " + temp.getCelsius()); System.out.println("The temperature in Kelvin is " + temp.getKelvin()); } }

7. Test Average and Grade Write a program that asks the user to enter five test scores. The program should display a letter grade for each score and the average test score. Write the following methods in the program: calcAverage: This method should accept five test scores as arguments and return the average of the scores. determineGrade: This method should accept a test score as an argument and return a letter grade for the score, based on the following grading scale: Score Letter Grade 90-100 A 80-89 B 70-79 C 60-69 D Below 60 F

import java.util.Scanner; public class TestAvgAndGrade { public static double calcAverage(double n1, double n2,double n3,double n4,double n5){ return (n1+n2+n3+n4+n5)/5; } public static String determineGrade(double avg){ if(avg<60){ return "F"; } else if(avg<70){ return "D"; } else if(avg<80){ return "C"; } else if(avg<90){ return "B"; } else { return "A"; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double n1, n2, n3, n4, n5; System.out.print("Enter test grade for student 1:"); n1 = scanner.nextDouble(); System.out.print(" Enter test grade for student 2:"); n2 = scanner.nextDouble(); System.out.print(" Enter test grade for student 3:"); n3 = scanner.nextDouble(); System.out.print(" Enter test grade for student 4:"); n4 = scanner.nextDouble(); System.out.print(" Enter test grade for student 5:"); n5 = scanner.nextDouble(); System.out.println(" The letter grades are as follows:"); System.out.println("Student 1: "+determineGrade(n1)); System.out.println("Student 2: "+determineGrade(n2)); System.out.println("Student 3: "+determineGrade(n3)); System.out.println("Student 4: "+determineGrade(n4)); System.out.println("Student 5: "+determineGrade(n5)); double avg = calcAverage(n1, n2, n3, n4, n5); System.out.printf("The average grade was: %.2f\n",avg); } }


Kaugnay na mga set ng pag-aaral

Chapter 10: Biodiversity 3- Animals

View Set