Convert the following Python 3 program into Java. You might want to run the Python program to see what the output should be. If you don't know Python, think of the following code as pseudo code.
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
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.
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
Write a program that asks the user for the number of days, and then prints out how many weeks (and days) that is.
For example, if the user entered 10, your program would output 1 weeks 3 days
. If the user entered 25, your program would output 3 weeks 4 days
. Note that you can use "weeks" and "days" for all inputs, even when it is grammatically incorrect.
Name this class DayConverter
Write a program that converts a recipe measurement in teaspoons (tsp.) and tablespoons (tbsp.) into milliliters (mL). Your code shoud ask the user for the number of teaspoons and tablespoons, and then print the total number of millilters in both. 1 tsp. = 4.9289 mL and 1 tbsp. = 14.7868 mL
For example, if the user enters 2 tsp. and 1 tbsp., then your program should print out 24.6446mL ( = 2*4.9289mL + 14.7868mL).
Name this class BakingConverter
Write a program that asks the user to enter their first and last name, separated by a space. This program then outputs a user ID, which is the first two letter of their first name, followed by the first four letters of their last name, followed by the number of characters in their full first and last name (but not counting the space). All letters in the user ID should be lower case.
You may assume that the first name is at least two letters long, and that the last name is at least 4 letters long.
For example, if the user entered "Jane Smith", then the user ID would be "jasmit9". If the user entered "Jose Rodriguez", then the user ID would be "jorodr13".
Name this class UserID
Write a program that asks the user for the zone and the ticket type, and displays the train fare.
Name this class TrainFare
Write a program that asks the user whether a team won or lost each of 10 games of some sport. The program then displays the number of games won, the number of games lost, the percentage of games won, and the percentage of games lost.
The user can use 'w' to indicate a win and 'l' to indicate a loss. For example, if the user enters:
Game 1: w Game 2: l Game 3: l Game 4: w Game 5: l Game 6: w Game 7: l Game 8: l
Then your code should display something like:
Number of wins: 3 Number of losses: 5 Percentage of games won: 37.5 Percentage of games lost: 62.5
If the user doesn't enter w or l, you can either ignore that game, or keep asking the user until they enter w or l.
Name this class SportsStats
Write a guessing game program that asks the user to guess a secret number. If the guess is too high or too low, the program should display a message saying so and ask the user to guess again. If the user guesses correctly, your program should congratulate them and end.
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
Extra challenge: Instead of always having the program exit when the user guesses the number, ask the user if they want to play again (and let them do so, if they say yes).
Extra hard challenge: Make your program cheat. That is, allow the program to change the secret number, so that it never contradicts the hints it has given before, but makes it take as long as possible for the player to win.
Write a method that takes in a String, and returns that same String, but with all the consonants in lower case and all the vowels in upper case.
For example, the String "apple" would be returned as "ApplE", the String "a frog" would be returns as "A frOg", and the String "Toronto" would be returned as "tOrOntO".
Call this method with at least three different inputs in the main method to test it.
Hint: We wrote a method to check if a character is a vowel in our Pig Latin translation program.
Name this class Capitalize
The Fibonacci numbers are the numbers in the sequence 1,1,2,3,5,8,13,21,... The sequence starts off with two 1s, and then each following number is the sum of the two numbers before it in the sequence. i.e. 2 = 1 + 1, 3 = 2+1, 5 = 3+ 2, etc.
Write a method that takes in a integer n, and uses a loop to print out the first n Fibonacci numbers if n is 0 or positive. The method should print out an error message if n is negative. The method should not return anything.
For example, if you pass 2 into the method, it should print "1,1". If you pass 5 into the method, it should print "1,1,2,3,5".
Call this method with at least three different inputs in the main method to test it.
Name this class Fibonnacci.
Extra challenge: Add another parameter to your method, so that it either prints out the first n Fibonacci numbers or it prints out only the n-th Fibonacci number.
Modify the Pig Latin program that we started writing in class to be able to translate all words into Pig Latin, not just those beginning with a vowel or a single consonant. You can either use the code you wrote in class, or down mine: code from class
Recall that you translate an English word into Pig Latin using these rules:
1) If the English word starts with one or more consonants, all consonants before the first vowel are removed from the front of the English word, and added to the end of it, keeping the order the same. The string “ay” is then added to the end of this string.
2) If the English word starts with a vowel, append the string “hay” to the end of that word.
Treat ‘y’ as a consonant.
For example, good becomes oodgay, egg becomes egghay, and school becomes oolschay.
Name this class PigLatin
Extra challenge 1: Change the rules for how you treat y. Treat it as a consonant if it is at the beginning of a word, and as a vowel if it is in the middle of a word.
Extra challenge 2: Ask the user for a sentence, and translate the whole sentence.
Write a program that displays the numbers from 1 to n in a grid of a certain size.
You should ask the user for n, as well as the number of columns for the grid.
For example, if the user tells you n=15, columns = 3, your program should display
something like
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
If the user tells you n = 10, columns = 3, your program should display something like
1 2 3
4 5 6
7 8 9
10
Name this class Numbers
Write a class Person that contains 3 instances variables:
Write the following methods for your class:
Test these methods in your main class by calling them at least three times.
Hint: if you haven't initialized the mother and father instance variables, then they will have the value null. So you could test if the mother of Person bart is known (that is, initialized), by testing if (bart.mother != null) { //then the mother variable has been initialized, and can be access as bart.mother }
Write a class BaseballPlayer that represents a baseball player. It should contain 4 private instances variables:
Write the following methods for your class:
Test all of these methods in your main class by calling them at least three times.
Write a class TodoItem that represents an item in a to-do list. It should have the following private instance variables:
The class should also have the following private static class variables, both initialized to 0:
Write the following methods for your class:
Test all of these methods (except the getters) by calling them at least three times in your main method.
Goal: Write a class and use it in a program. Review of loops.
For this problem set, you will write a class GameCharacter that represents a character, either good or bad, in a video game. You will then use this class to write a simple game in which the player fights a monster. Both the player and the monster will be represented as instances of GameCharacter.
Create a class GameCharacter that contains 3 private instances variables:
Write the following methods for your class:
Write a static method test() in GameCharacter that calls each of the above methods at least three times to test them. Call test() at the beginning of the main() method to test your code. Make sure that your code is working before continuing.
Once your code in GameCharacter is working, comment out the call to test().
In the main() method of GameCharacter, write a program in which the user's character fights a monster. The code should start by asking the player for the name of his/her character, saying that the monster is attacking, and then at each turn, ask the user if they are attacking or defending. The monster always attacks. The fight should continue until either the player or the monster is unconscious/dead (has health <=0). Both the player and monster should be represented in the code as instances of GameCharacter.
Here are more specific instructions:
Extra challenge: Make this game more interesting by using random numbers (http://docs.oracle.com/javase/8/docs/api/java/util/Random.html) for the initial health of the characters, and for the damage done during attacks.
Add a (non-static) equals(..) method to your class BaseballPlayer from Problem Set 8. This method should take in a single BaseballPlayer instance as a parameter, and return true if the name and team are the same as in the calling instance.
Instead of your version, you can use the BaseballPlayer class I posted as the solution instead, but should say so in the comments.
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].
Test your method by calling it in the main(..) method with at least three different input arrays.
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.
Test your method by calling it in the main(..) method with at least three different input arrays.
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.
Test your method by calling it in the main(..) method with at least three different input arrays.
Name this class SymMatrix.
Name this class SymMatrix.
Write a class TodoList that represents a to-do list. It will use the TodoItem class from previous homework. You can either use your version of this class, or download and use the version posted as a solution.
The TodoList class should contain two instance variables:
Since we must give an array a size when we initialize it, we (arbitrarily) set the size of the array representing the to-do list to be 100. That is, we can have up to 100 items in our to-do list. Many to-do lists have less than 100 items in them, so we have another variable that keeps track of exactly how many TodoItem instances are in the array. We will assume that the first numItems elements of the array are TodoItem instances, and the remaining elements are null.
Write three methods for this class:
Test these methods by calling them each at least three times.
For this homework, you will create two subclasses of your class GameCharacter in homework 10. You can either use your version of GameCharacter, or you can download the one posted as the solution. The instructions below are the minimal requirements, but feel free to make a more elaborate game.
The first subclass will represent the player's character. You can call this subclass Player, or you can call it a specific type of player character, like Fighter or Wizard. I will call it Player below.
Create this subclass, and write the following methods:
As in the GameCharacter homework, test these methods by writing a method test2 in GameCharacter that calls them each at least three times. Call test2 in the main method in GameCharacter to perform the tests (and then comment it out).
Next create a subclass of GameCharacter called Monster (or a specific kind of villan like Ogre or Alien).
For this subclass, write the following methods:
Again, test these methods by calling them at least three times in the method test2.
Finally, modify the main method of GameCharacter so that the player is an instance of the Player class, and the monster is an instance of the Monster class. The player should now have the choice of attacking, performing the special attack, or defending each round. The monster should randomly chose between attack and specialAttack each round.
Submit your GameCharacter, Player, and Monster class.
Goal: Practice implementing the Comparable interface and overriding the equals(Object obj) method.
Create a class called Movie, which represents a movie, and which has the following variables:
title
, which is a String representing the title of the moviea) Write a constructor for the class Movie that takes in as parameters Strings representing the title and studio of the movie.
b) Write a toString() method for the class Movie, which returns a String with the title and studio, nicely formatted.
c) Implement the Comparable interface for the class Movie. The method CompareTo
should be written so that an array of Movies will be sorted first by studio, and then by title.
Test your CompareTo method by creating three different arrays of Movie instances, and sorting them (use Arrays.sort(...)).
d) Override the default equals(Object obj) method, so that two instances of a Movie are considered equal if they have the same studio and if their titles are the same (ignoring case). For example, movie instances with the titles "Lion King" and "Lion king" should be considered equal, if their studio is the same.
Test your equals method by calling it on three different test cases. Additionally, if you create two arrays of Movie instances, you can now compare them by calling Arrays.equals(..), which will call your equals method to test the pairs of instances.
This is a continuation of problem sets 9 and 13. You may either use your own TodoItem and TodoList classes, or the ones posted as solutions (or a combination of the two).
a) Make TodoItem implement the Comparable<TodoItem> interface. To do this, you will need to write the method compareTo, which should compare two TodoItems based on their due date (you can assume all items have the same year).
Test your compareTo method by calling it three times in the main() method.
b) Write a method sort in TodoList that takes in no parameters and sorts the items in your to-do list (the TodoItem array). You can use Arrays.sort(...), which will use the compareTo method you wrote in part a.
Test this method on three different to-do lists.
In a new class, implement the following psuedocode method mystery. Call it several times from the main() method to see what it does.
function mystery(num) {
if num <= 0 then return 1 return 3*mystery(num -1) }
In a new class, implement the following psuedocode method mystery. Call it several times from the main() method to see what it does.
function mystery( num ) { if num<2 { print num return } mystery(num/2) print num % 2 }
Note: For this mystery function, print should not add a newline at the end.
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".
Test your method.
For this problem, you will use the Person class you wrote for problem set 7. You can either use your own version or the one posted as the solution. Recall that a Person has a name, and a mother and a father, which will also be Person instances, if they are known.
Write a non-static recursive method findAncestor that takes in a String, representing a name. This method should return true if the calling instance (this) or any of the calling instance's known ancestors have that name, and false otherwise.
For example, if you look at the Person class posted as the solution for problem set 7, you will see that it makes instances for Bart, Marge, Homer, and Grampa Simpson. For these instances, calling bart.findAncester("Grampa Simpson") should return true, while calling bart.findAncester("Lisa") should return false. Note that the family tree could go back many generations, so you will have to use recursion to search it.
Test your method by calling it at least three times.
Write a recursive method that takes in an number n and prints out n stars (*). For example, if your method takes in the number 5, it should print out *****.
Test your method.
The two classes File.java and Directory.java represent a file and a directory, respectively, in a simulated file system.
The File class has one instance variable, a String called name, which holds the name of the file.
The Directory class has 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 null (empty). The File and Directory instances in these arrays represent the contents of this Directory (i.e. the files and directories that it contains).
Look at the test case in the main method of Directory. This simulates a file system with the base directory "Dir 6". "Dir 6" contains the file "File 9" and the sub-directories "Dir 4" and "Dir 5". Directory "Dir 5" contains no files and no directories. Directory "Dir 4" contains files "File 7" and "File 8" and directory "Dir 3". So "Dir 6" contains file "File 8" two levels down, etc.
Complete the recursive method containsFile(..) in Directory. This method takes in a String representing a filename, and returns true if a File with that filename is contained somewhere (possibly in a sub-directory, sub-sub-directory, etc.) in the calling Directory.
Hint: it might help with debugging to write a toString method for each class.
Write a program that asks the user for the name of a input file, an output file, and a letter. Write each line of the input file to the output file, followed by the number of times that the letter appears in that line.
Name this class LetterCount
This problem continues problem sets 9, 13, and 16. You may either use your own TodoItem and TodoList classes, or the ones posted as solutions (or a combination of the two).
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 instantiate an instance of TodoList with the information in the file. That is, for each line in the file, you should make a new TodoItem in the array in TodoList.
b) Write a method that writes the TodoList instance to a file in the format you chose in part (a) above. (Hint: change your toString() method if necessary, to make things easier)
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 4 to use Exceptions to handle invalid guesses i.e. if they enter a word instead of a number. (You can also write a new version of the whole program.)
Your code should catch the above Exceptions, show the user an error message, and ask the user to re-enter their guess.