Convert the following Python 3 program into Java. You might want to run the Python program to see what the output should be.
def main(): rad1 = 18 rad2 = 19 pi = 3.14 print( "The diameter of the first circle is", 2*rad1 * pi ) print( "The diameter of the second circle is", 2*rad2 * pi ) print( "The area of the first circle is", rad1 * rad1 * pi ) print( "The area of the second circle is", rad2 * rad2 * pi ) print( "The ratio of the two radii is", rad1 / rad2 )
Name this class Circles
Place the class in the edu.cuny.lehman.cmp326 package.
A madlib is a word game played by one person asking the others for specific types of words (i.e. noun, verb, exclamation), and using them to fill in the blanks in a sentence. This results is a bizarre, but hopefully funny, sentence. (Wikipedia page on Mad Libs)
Write a program that asks the user for the required type of word to fill in four blanks in a sentence or two. The program should then display the filled in sentence(s) to the user. You may use the example sentence below, or make up your own. As in problem 1.1, you may use either a GUI or the keyboard scanner and output console.
Example output might be:
Enter an adjective: white Enter an adjective: silly Enter a person: aunt Enter an event: Santa Claus parade Here's your sentence: It was a white and silly night, but I still managed to make it to the house of my aunt to watch the Santa Claus parade.
Name this class MadLibs
Place the class in the edu.cuny.lehman.cmp326 package.
Write a program that asks the user for distance in feet and prints the number of yards and feet (assume that there are 3 feet to the yard). For example, if the user entered, 10, your program would output 3 yards 1 feet
. Note that you should use "yards" and "feet" for all inputs (even in the cases where it is grammatically incorrect).
Name this class LengthConverter
Place the class in the edu.cuny.lehman.cmp326 package.
Convert the following pseudocode into Java. Debug it and make sure there are no errors in the pseudocode.
// converts from stone to kg. 1 stone == 14 lbs. 1 lb. == 0.453592 kg. main(){ get input from user and assign to stones lbs = stones * 14 kg = lbs * 0.453592 print out total number of kilograms }
Name this class MassConverter
Place the class in the edu.cuny.lehman.cmp326 package.
Write a (static) method that allows the user to convert a temperature, given in degrees, from either Celsius to Fahrenheit or Fahrenheit to Celsius. Use the following formulas:
Degrees_C = 5(Degrees_F - 32)/9
Degrees_F = (9/5)Degrees_C + 32
Prompt the user to enter a temperature followed by either “C” or “c” for Celsius or a temperature followed by “F” or “f” for Fahrenheit. Convert the temperature to Fahrenheit if Celsius is entered, or to Celsius if Fahrenheit is entered. Display the result in a readable format. If anything other than a number followed by “C”, “c”, “F”, or “f” is entered, print an error message and stop.
Name this class TemperatureConverter
Place the class in the edu.cuny.lehman.cmp326 package.
Hint: Since 9 and 5 are both ints, (9/5) will evaluate to 1 in Java, which is not what we want.
Write a function that takes as two parameters: the zone and the ticket type, and returns the BART fare.
Include a main() that calls your function several times to demonstrate that it works. Make sure to test for inappropriate inputs.
Name this class BARTFare
Place the class in the edu.cuny.lehman.cmp326 package.
Suppose we attend a party. To be sociable, when we arrive, we will shake hands with
everyone who is already at the party. Write a program that prompts the user for the
total number of guests at a party. Using a for
loop, your
program will compute and display the number of handshakes that occur as each guest
arrives. Your program should also compute and display the total number of handshakes
that occur after all guests have arrived. (Hint Upon arrival, each person shakes
hands with everyone that is already there. You can assume that there is only one host
for the party). Your output format should exactly match this output format:
How many guests are invited to the party: 5 When Guest 1 arrives, Handshakes=1, Total Handshakes=1 When Guest 2 arrives, Handshakes=2, Total Handshakes=3 When Guest 3 arrives, Handshakes=3, Total Handshakes=6 When Guest 4 arrives, Handshakes=4, Total Handshakes=10 When Guest 5 arrives, Handshakes=5, Total Handshakes=15
Name this class HandShakes
Place the class in the edu.cuny.lehman.cmp326 package.
(Exercises #10, Page 249) Write a program that will compute statistics for eight coin tosses. The user will enter either an h for heads or a t for tails for the eight tosses. The program will then display to total number and percentages of heads and tails. Use the increment operator to count each h or t that is entered. For example, a possible sample dialogue between the program and the user might be:
For each coin toss enter either h for heads or t for tails. Toss 1: h Toss 2: t Toss 3: t Toss 4: h Toss 5: t Toss 6: h Toss 7: t Toss 8: t Number of heads: 3 Number of tails: 5 Percent heads: 37.5 Percent tails: 62.5
Name this class CoinTosses
Place this class in the edu.cuny.lehman.cmp326 package.
For all the following words, if you move the first letter to the end of the word, and then spell the word the result backwards, you will get the original word:
banana dresser grammar potato revive uneven assess
Write a program that asks the user for one word at a time and determines whether it has this property. Continue asking for and testing words until the user enters the word quit. Treat upper case letters as lowercase letters.
Name this class CheckWords
Place this class in the edu.cuny.lehman.cmp326 package.
Write a program that prompts the user for a beginning bank balance and an interest rate. The program will display the value of the account at the end of each year for 10 years. The output should show the value of the account for three different methods of compounding interest:
Your program should allow the user to perform the calculation multiple times for different starting balances. A negative starting balance indicates that the user is done.
Sample output:
Enter initial balance: 1000 Enter apr: .05 After 1 year Annually compounded: 1050.0 Monthly compounded: 1051.16 Daily compounded: 1051.27 After 2 years Annually compounded: 1102.5 Monthly compounded: 1104.94 Daily compounded: 1105.16 After 3 years Annually compounded: 1157.63 Monthly compounded: 1161.47 Daily compounded: 1161.82 After 4 years Annually compounded: 1215.51 Monthly compounded: 1220.9 Daily compounded: 1221.39 After 5 years Annually compounded: 1276.28 Monthly compounded: 1283.36 Daily compounded: 1284.0 After 6 years Annually compounded: 1340.1 Monthly compounded: 1349.02 Daily compounded: 1349.83 After 7 years Annually compounded: 1407.1 Monthly compounded: 1418.04 Daily compounded: 1419.03 After 8 years Annually compounded: 1477.46 Monthly compounded: 1490.59 Daily compounded: 1491.78 After 9 years Annually compounded: 1551.33 Monthly compounded: 1566.85 Daily compounded: 1568.26 After 10 years Annually compounded: 1628.89 Monthly compounded: 1647.01 Daily compounded: 1648.66 Enter initial balance: 2000 Enter apr: .05 After 1 year Annually compounded: 1710.34 Monthly compounded: 1731.27 Daily compounded: 1733.19 After 2 years Annually compounded: 1795.86 Monthly compounded: 1819.85 Daily compounded: 1822.04 After 3 years Annually compounded: 1885.65 Monthly compounded: 1912.96 Daily compounded: 1915.46 After 4 years Annually compounded: 1979.93 Monthly compounded: 2010.83 Daily compounded: 2013.66 After 5 years Annually compounded: 2078.93 Monthly compounded: 2113.7 Daily compounded: 2116.89 After 6 years Annually compounded: 2182.87 Monthly compounded: 2221.85 Daily compounded: 2225.42 After 7 years Annually compounded: 2292.02 Monthly compounded: 2335.52 Daily compounded: 2339.51 After 8 years Annually compounded: 2406.62 Monthly compounded: 2455.01 Daily compounded: 2459.45 After 9 years Annually compounded: 2526.95 Monthly compounded: 2580.61 Daily compounded: 2585.54 After 10 years Annually compounded: 2653.3 Monthly compounded: 2712.64 Daily compounded: 2718.1 Enter initial balance: -1 Done.
Name this class BankInterest
Place this class in the edu.cuny.lehman.cmp326 package.
Hint: Remember that an int divided by an int is an int (but you might not want it to be).
Write a program that asks the user to enter a series of five-letter words. Keep asking until the user enters an empty string. If the word they enter is not five letters, don’t use that word, and prompt them again. You will then collect the first letters from each word into a variable, the second letters into a variable, etc. At the end, print the five variables in order.
Here is some sample output:
Please enter a five-letter word (<enter> to end): Frank Please enter a five-letter word (<enter> to end): banjo Please enter a five-letter word (<enter> to end): bank That's not five letters! Please enter a five-letter word (<enter> to end): hello Please enter a five-letter word (<enter> to end): bingo Please enter a five-letter word (<enter> to end): wordy Please enter a five-letter word (<enter> to end): Fbhbw raeio anlnr njlgd koooy
Name this class ListCities
Place the class in the edu.cuny.lehman.cmp326 package.
Write a guessing game program that asks the user to guess your secret number. If the guess is too high, write a message saying so and ask them to guess again. Similarly, if the guess is too low, write a message saying so and ask them to guess again. If they guess correctly, congratulate them and end the program. You can assume the user will only enter integers.
You can either fix the secret number in your code, or you can use methods from the class Random to generate a random secret number. You will have to import java.util.Random to use this class.
Name this class GuessingGame
Place the class in the edu.cuny.lehman.cmp326 package.
Write a class for a video game character. The character should have a name, a type (scout, soldier, medic, etc.) and current health. Therefore it needs three attributes:
String name
String type
int health
This class should have the following methods:
GameCharacter( String newName, String newType, newCurHealth )
changeHealth( int change )
change
amount, so it will go down if change
is negative, and up if it’s positive. If the health goes below 0, changeHealth
should return the String "Your character is dead"
.
Name this class GameCharacter. Write a main method to test your code. Each method should be tested at least 3 times.
Place the class in the edu.cuny.lehman.cmp326 package.
Consider a class that keeps track of the sales of an item. An object of this class will have the attributes (variable names in parentheses):
numSold
)
totSales
)
totDisc
)
itemCost
)
bulkQuant
)
bulkDiscPct
)
And the following constructors:
ItemSales()
ItemSales(double itemCost)
Implement this class in Java. (What types should the variables be? What values should the variables be initialized to in each contructor?) Implement get
and set
methods for all attributes, as well as a toString
method. Now write a main
method to test your setters and getters. Make sure you test all the possibilities (e.g., what happens if you try to set a negative cost per item?). Also be sure the output is clear for your users.
Name these classes ItemSales & ItemSalesDemo
Place both classes in the edu.cuny.lehman.cmp326 package.
Now we’ll expand the ItemSales class that was started in part a. Add the following methods:
ItemSales(double itemCost, int bulkQuantity, double discountPecentage)
ItemSales(int bulkQuantity, double discountPercentage)
registerSale(n)
n
items.
If n
is equal to or larger than the bulk quatity, the cost per item
will be reduced by the bulk discount.
displaySales()
equals(ItemSales otherItem)
Update your main
method to test your setters and getters. Make sure you test all the possibilities (e.g., what happens if you try to sell an item that hasn’t had a price set, yet?). Again, be sure the output is clear for your users.
Implement a class PersonAddress that represents an entry in an address book. Its attributes are:
Consider a class Characteristic
that will be used in an online
dating service to assess how compatible two people are. Its attributes are:
And the following methods:
isValid(aRating)
that returns true if the given rating is valid, that is, it is between 1 and 10
setRating(aRating)
that sets the rating to aRating
if it is valid
setRating()
that reads a rating from the keyboard. If the rating entered is not valid, keep asking the user until they enter one that is valid.
get
, and set
methods for all attributes (except the setter for rating
, which was done above).
Implement this class in Java and write a main() method within it to test it.
Name this program Characteristic
Place both classes in the edu.cuny.lehman.cmp326 package.
Write a program that asks the user for the number of items purchased, and then the prices of those items. The program should then print out each price and the total, formatted nicely. Here is a sample run of the program:
Please enter the total number of prices: 5 Please enter a price (<enter> to end): 2.34 Please enter a price (<enter> to end): .99 Please enter a price (<enter> to end): 100 Please enter a price (<enter> to end): 81.05 Please enter a price (<enter> to end): 90 Please enter a price (<enter> to end): Your receipt: 2.34 0.99 100.00 81.05 90.00 ---------------- Total: 274.38
There are a few different ways to format numbers in Java, some of them similar to formatting in Python. See this tutorial.
Name this class ListPrices
Place the class in the edu.cuny.lehman.cmp326 package.
Write a static method which takes an array of ints as its argument, and reverses the order of the elements in the array. That is, the first and last elements are switched, the second and second last elements are switched, etc. For example, this method should change the array [1, 2, 3, 4] to the array [4, 3, 2, 1].
Write a driver file to test your method. It should call your method with at least three different inputs.
Hint: When an array is passed into a method as a parameter, what is passed in is the reference to the location of that array in memory, not the array itself.
Name this class ReverseArray
Consider the class Athlete, which is available here. Add a static method to the class which takes an array of Athletes as its argument, and returns the total number of medals won by all athletes stored in the array. Change the package of Athlete.java if needed.
Write a driver file to test your method. It should call your method with at least three different inputs.
Upload the modified class Athlete.java
Write a static method which takes a 2-dimensional array of type int, which represents a matrix, as its argument, and returns true if the matrix is symmetric and false otherwise. A matrix is symmetric if the entry at row i and column j is the same as the entry at row j and column i for each i and j. The diagonal entries (i.e. entries with the same row and column) can be any number.
Write a driver file to test your method. It should call your method with at least three different inputs.
Name this class SymMatrix.
Create a class called Book, which has the following variables:
a) Write a constructor for the class Book that takes in as parameters Strings representing the title and author of the book. Test this method by creating three different instances of type Book.
b) Write the method toString() for the class Book which prints out the title of the Book, followed by " by ", and then the author. If the title of the book is "Never Cry Wolf", and the author of the book is "Farley Mowat", then its toString() method would return the String "Never Cry Wolf by Farley Mowat". Test this method by printing out the information for the three instance of Book created in part (a).
c) Create a subclass of Book called Textbook. This subclass should have one additional variable: subject, which is a String representing the subject of the textbook. Write the constructor for Textbook that takes in as its parameters Strings representing the title, author, and subject of the TextBook. Test this method by creating three different instances of type Textbook.
d) Write a toString() method that returns a String containing information (title, author, subject) about a Textbook. You can decide how to format the String. Test this method by printing out the information for the three instance of TextBook created in part (a).
e) Write a method which takes in an array of Books and returns an array of TextBooks that contains exactly those Books in the input array which are also TextBooks.
You are going to write two classes that will work together to represent a to-do list. This is the first part, and we will write the first class and test it.
a) Create a class TodoItem that represents an item on a to do list. It should be able to store the following information in its instance variables:
b) Write getters and setters for your instance variables in TodoItem. The setters should only set the instance variables to valid values. If the value passed to the setter is not valid (for example, if the priority of an item is represented by a number between 1 and 5, and the number 6 is passed to the setter), then the setter should print an error message and the program should exit.
c) Write a toString() method for TodoItem.
d) Make TodoItem implement the Comparable\
e) Write a driver to test the above code. To test the compareTo method, create three different arrays of TodoItems and sort them using Arrays.sort(...)
a) Create a class TodoList which contains an ArrayList of TodoItems. This will represent the to-do list.
b) Write a method for adding an item to the to-do list. It should take in parameters for the to-do list item, the priority, and the due date. The method should then use these parameters to create a new TodoItem and add it to your ArrayList.
c) Write a method that sorts the items in your to do list using the compareTo method you wrote in TodoItem. Use the fact that ArrayList implements the List interface, and the Java class Collections has a method to sort classes implementing the List interface.
d) Test the above methods with at least three test cases each.
You are in downtown Manhattan, and would like to walk a certain number of blocks east and south. Write a method using recursion that will calculate the total number of possible paths. For example, if you wanted to go 1 block east and 2 blocks south, you could walk either:
For simplicity, assume that you never walk north or west, Broadway doesn't exist, and that there are an infinite number of blocks in both directions in downtown Manhattan (so you can pass in any positive integers as the arguments).
Write code to test your method.
Hint: If you going five block east and five blocks south, say, then the total number of paths is equal to the total number of paths to go five blocks east and four blocks south plus the total number of paths to go four blocks south and five blocks east.
Write a recursive method that takes in a String and returns a new String in which any consecutive characters that are the same have been replaced by only one of that same character. For example, if your method takes in the String "Hello", it should return the String "Helo". If it takes in the String "abbcccdddda", it should return the String "abcda".
Write code to test your method.
The first class should be called File, and have one instance variable called filename, which is a String.
The second class should be called Directory, and have two instance variables. The first is an array of File objects, and the second is an array of Directory objects. Note that either of the arrays can be empty.
To simulate a file system with these classes, you will have a starting Directory. The Directory instances in the array represent sub-directories in the file system, and the File instances in the array represent files in that directory. Each of the sub-directories, might also contain files and sub-directories, etc.
Write a recursive method that takes in a String, representing a filename, and a Directory, representing the starting directory. This method should return true if a File with that filename is contained somewhere (possibly in a sub-directory, sub-sub-directory, etc.) in the starting Directory.
a) Modify your TodoList class so that it can read in a file each which each line represents a to do list item (you can decide on the format for the file), and initialize an instance of TodoList with the information in the file.
b) Write a method that writes the TodoList instance to a file in the format you chose in part (a) above.
c) Write a main method that asks the user for a to do list file, reads it into your program, sorts the to do list, and writes the sorted to do list to a file.
Rewrite your Guessing Game program from Problem Set 3b to use Exceptions to handle invalid guesses. (You can also write a new version of the whole program.)
Specifically, once the user enters a guess, you should throw an exception if the guess is out of range. i.e. if the user is told to guess a number between 1 and 100, but enters 1001, then the code should thrown an exception with a helpful error message. Your code should also throw an exception if the user input is invalid (i.e. they enter a word instead of a number).
Your code should also catch the above Exceptions, show the user an error message, and ask the user to re-enter their guess.
Hint: One way to do this is to write a helper method which asks the user for their guess, and either returns a valid guess or throws an Exception. You can then call this helper method from your main method, using a try-catch block to handle any Exceptions.
Currently you are handling errors in your To do list program by printing an error mesage to the screen and exiting. Instead, have any method that catches an error in this fashion instead throw an Exception. Catch all Exceptions in your main method.