Java代写:COMP202 Countdown Days

代写Java基础作业,实现要求的函数方法。

Part 1: Warm-up

Do NOT submit this part, as it will not be graded. However, doing these exercises might help you to do the second part of the assignment, which will be graded. If you have difficulties with the questions of Part 1, then we suggest that you consult the TAs during their office hours; they can help you and work with you through the warm-up questions. You are responsible for knowing all of the material in these questions.

Warm-up Question 1

Write a method getFirstHalf() that takes as input a String and returns a String composed of the first half of the characters from the specified String. For example, getFirstHalf("cucomber") returns the String “cuco”, while getFirstHalf("apple") returns the String “ap” (thus, if the number of characters is odd, you should round down).

Warm-up Question 2

Write a method alphaString() which takes two Strings as input and returns the String between the two that comes first in the alphabet. For example, alphaString("banana", "apple") returns the String “apple”, while alphaString("snake", "squirrel") returns the String “snake”.

Warm-up Question 3

Write a method replaceAll() which takes as input a String and two characters. The method returns the String composed by the same characters of the given String where all occurrences of the first given character are replaces by the second given character. For example, replaceAll("squirrel", 'r', 's') returns the String “squissel”, while replaceAll("squirrel", 't', 'a') returns the String “squirrel”.

Warm-up Question 4

Write a method generateRadomArray(0 that takes as input an integer n and returns an array of size n. The elements of the array should be random doubles between 0 (included) and 5 (excluded). You can use Math.random() to do this.

Warm-up Question 5

Write a method getLargestElement() that takes an array of integers as input and returns the largest element inside the array. For example, if the input is: int[] arr= {1, 5, -3, 15, 4}; then getLargestElement(arr) should return 15.

Warm-up Question 6

Write a method getSum() that takes an array of integers as input and returns the sum of all the elements inside the array. For example, if the input is: int[] arr= {1, 5, -3, 15, 4}; then getSum(arr) should return 22.

Warm-up Question 7

Write a method countNegatives() that takes an array of integers as input and returns the number of negative numbers inside the array. For example, if the input is: int[] arr= {1, 5, -3, 15, -13}; then countNegative(arr) should return 2.

Part 2

The questions in this part of the assignment will be graded.

Throughout this assignment you are allowed to use everything we have learned in class up to and including arrays and Scanner. This does not mean however that you are allowed to change any of the headers of the methods described below. You need to make sure to follow precisely the instructions provided (for example, you’ll be using Scanner only in one of the methods for this assignment!).

For this assignment, you are NOT allowed to use the following:

  • Any other method from the String class beside length(), charAt(), equals(), equalsIgnoreCase(), toLowerCase(), and toUpperCase().In particular, you are not allowed to use substring().
  • Any other class beside Scanner.

We have imported other classes to provide you with some useful methods. You should not touch the code provided, you should simply use it.

Question 1: CountdownDays

For this question, you will write a program that displays the number of days left between now (when the program is run) and a given due date provided by the user. To do that, you will need to implement all the methods listed below. All the code for this question must be placed in the file named CountdownDays.java provided with these instructions. In this file, you will be provided with a method called getCurrentDate(). You should NOT modify such method in any way. The method takes no input and returns a String representing the current date. You should use this method to help you implement the one of the methods listed below.

Note that throughout this question, you can assume that a String representing a date has the following format: “dd/mm/yyyy”. So, for instance, Strings such as “04/09/2034” and “30/01/1234” correctly represent a date, while “03/23/2018” or “1998/09/10” do not. Throughout this question, when we refer to a String that represents a date you can assume that such String is correctly formatted.

Note that you are free to write more methods if they help the design or readability of your code.

1a. A method to get a substring from a specified String

Write a method called getSubstring that takes a String s and two integers i and j as input. The method should throw an IllegalArgumentException (with an appropriate message) if the second integer is smaller than the first one. Otherwise, the method returns the String composed by all the characters from the input String s that are within the positions i and j, including both of them. For example,

  • getSubstring(“strawberry”, 0, 4) returns “straw”
  • getSubstring(“cats and dogs”, 3, 6) returns “s an”
  • getSubstring(“monday”, 2, 2) returns “n”
  • getSubstring(“another string”, 6, 3) throws an IllegalArgumentException.
  • getSubstring(“more cats”, -4, 3) naturally (i.e. you don’t have to do anything about it) throws a StringIndexOutOfBoundsException.

1b. Three different methods to extract day, month, and year from a String

Write the following methods:

  • getDay()
  • getMonth()
  • getYear()

all the above methods take a String as input. You can assume that such String represents a date and it is properly formatted (see definition in the preamble). All three methods return an integer: getDay() returns the integer representing the day of the specified date, getMonth() the integer representing the month of the specified date, and getYear() the integer representing the year of the specified date. For example:

  • getDay(“04/09/2034”) returns 4.
  • getMonth(“04/09/2034”) returns 9.
  • getYear(“04/09/2034”) returns 2034.

To get full marks, your methods must call getSubstring().

1c. A method to check if a year is a leap year

Write a method isLeapYear() which takes one integer as input representing a year. You can assume that the input represents a valid year (i.e. it is a positive integer). The method returns true if the year is a leap year, false otherwise. Note that, a year is a leap year if it is divisible by 4, except for century years which must be divisible by 400 in order to be leap. For example 1988, 1992, 2000, 2096 are leap years and 1985, 2002, 2100 are not leap years.

1d. A method that returns the number of days in a month

Write a method getDaysInAMonth() which takes two integer as input, one representing a month and the other representing a year, respectively. You can assume that the inputs are valid (i.e. they are both positive integers and the one representing the month is greater than or equal to 1 and less than or equal to 12). Note that for the months, the number 1 represents January, 2 February, 3 March, and so on. The method returns the number of days in the given month. Remember that the month of February in a leap year has 29 days, instead of the usual 28.1 For example:

  • getDaysInAMonth(4, 2018) returns 30.
  • getDaysInAMonth(2, 1992) returns 29.
  • getDaysInAMonth(1, 1853) returns 31.

To get full marks your method must call isLeapYear().

1e. A method to check whether the due date has passed

Write a method dueDateHasPassed() which takes two Strings as input. You can assume that the two Strings correctly represent a date. The first input represents the current date, while the second one represents the due date. The method should return true if the due date represents a date that comes earlier or is equal to the current date. The method returns false otherwise. To get full marks your method must call the three methods, getDay(), getMonth(), and getYear() described above. Hint: when comparing two dates you should start by comparing the years, followed by the months, followed by the days. For example:

  • dueDateHasPassed(“12/04/1998”, “23/01/2002”) returns false.
  • dueDateHasPassed(“23/01/2002”, “12/04/1998”) returns true.
  • dueDateHasPassed(“23/01/2002”, “23/01/2002”) returns true.

1f. A method to count the number of days left before the due date

Write a method countDaysLeft() which takes two Strings as input. You can assume that the two Strings correctly represent a date. The first input represents the current date, while the second one represents the due date. The method returns an integer representing the number of days between the current date and the due date. If the due date has passed, the method should return 0, otherwise it should count exactly how many days are there between the current date and the due date. When doing so, it is easier to go through the all the years, then the months, and finally the days separating the current date to the due date. Note that years might have a different amount of days depending on whether or not they are leap years. More over, months too have different number of days depending on the actual month and whether or not it is part of a leap year. To get full marks your method must use all of the methods defined above beside getSubstring() (which you are free to use, but it is not necessary to do so). For example:

  • countDaysLeft(“13/10/2018”, “23/10/2018”) returns 10.
  • countDaysLeft(“13/10/2018”, “08/05/2024”) returns 2034.
  • countDaysLeft(“13/10/2018”, “15/09/2018”) returns 0.
  • countDaysLeft(“13/10/2018”, “18/09/2019”) returns 340.
  • countDaysLeft(“13/10/2018”, “26/02/2019”) returns 136.

1g. A method to diplay the countdown required

Write a method displayCountdown() which takes one String as input that represents a due date. As always throughout this question, you can assume that the String is correctly formatted. The method should retrieve the current date using the method getCurrentDate() provided to you. It should then obtain the number of days left before the due date using the method countDaysLeft() described above. The method finally displays the following information:

  • Today’s date (the current date).
  • The due date.
  • An encouraging message displaying the number of days left until the due date if such number is greater than 0. A message informing the user the due date has passed otherwise.

1h. Setting up the main method (Optional - No extra marks)

Set up the main method so that the program receives one input through command line argument. The input should be a String representing a date in its correct format. You can then call displayCountdown() with the appropriate input and see the countdown displayed by your method (as in the examples above).

Question 2: GuessTheWord

For this question, you will have to write a Java program that implements a game in which the player needs to guess a randomly generated secret word. The players will have to guess such word by guessing one character at a time. Each time they guess a character that is not contained in the secret word they lose a life. The player has 10 lives and their goal it to guess the word before “dying”.

To complete this task, you will need to implement all the methods listed below. All the code for this question must be placed in the file named GuessTheWord.java which was provided to you. In this file, you will be provided with a method called getRandomWord(). You should NOT modify such method (or any of the code in the file) in any way. The method takes an integer as input and returns a String representing the word to be guessed. You should use this method to help you implement the one of the methods listed below. Note that you are free to write more methods if they help the design or readability of your code.

Note that throughout the question you can assume that the word to be guessed contains only lower case letters of the English alphabet.

2a) Method to check if the guess is valid

Write a method isValidGuess that takes as input a character representing the guess made by the player. The method returns true if such character is a lower-case letter of the English alphabet, false otherwise. For example:

  • isValidGuess(‘g’) returns true
  • isValidGuess(‘B’) returns false
  • isValidGuess(‘!’) returns false

2b) Method to generate the array of guesses

Write a method generateArrayOfGuesses() that takes as input a String representing the word to be guessed. The method returns an array of integers that the program will use to keep track of which character of the String has already been guessed by the player. At the very beginning none of the characters were guessed. To do so the method returns an array that has as many elements as the number of characters in the specified String. To indicate that none of the characters has been guessed yet, all the elements are initialized with value equal to 0. So, for example, generateArrayOfGuesses(“pineapple”) returns the array {0, 0, 0, 0, 0, 0, 0, 0, 0}.

2c) Method to check the guess and update the array if needed

Write a method checkAndUpdate() that takes as input a String representing the secret word, an array of integers representing the guesses made by the player, and a char representing the last guess made by the player. For the purpose of this method, you can assume that the guess is valid (i.e. it is a lower case letter of the English alphabet). The method should check if the guess provided is indeed a character contained in the secret word. If so, the method updates the array by assigning the value 1 to the element corresponding to the position of the given character inside the secret word. In this case, the method should also return true confirming that the guess was indeed a good one. Otherwise, if the character provided is not contained in the secret word, the method simply returns false.

For example, consider the following array:

1
int[] guesses = {0, 0, 0, 1, 0, 0, 0, 0, 1};

Note that the array indicates that the character ‘e’ has already been guessed by the player. Then:

  • checkAndUpdate(“pineapple”,guesses,’t’) returns false and leaves the array unchanged.
  • checkAndUpdate(“pineapple”,guesses,’i’) returns true and updates the value of the second element with 1.
  • checkAndUpdate(“pineapple”,guesses,’p’) returns true and updates the values of the first, the sixth, and the seventh element with 1.
  • checkAndUpdate(“pineapple”,guesses,’e’) returns true (even if the character had already been guessed!) and updates the values of the fourth, and ninth element with 1.

2d) Method to get the String to display

Write a method getWordToDisplay that takes as input a String representing the secret word, an array of integers representing the guesses made by the player, and a char representing the last guess made by the player. For the purpose of this method, you can assume that the guess is valid (i.e. it is a lower case letter of the English alphabet). The method returns a String representing the sequence of characters that the player can now see after the last guess has been made. Such String is built by going through all the characters of the secret word and:

  • If the character matches with the last guess made by the player, then it is replaced by the same letter but in upper case.
  • If the character does not match with the last guess, but it has been previously guessed by the player, then it is kept as is.
  • Finally, if the character has not been guessed by the player yet, then it should be replaced by the hyphen ‘-‘ character.

For example, consider the following array:

1
int[] guesses = {0, 0, 0, 1, 0, 0, 0, 0, 1};

Then:

  • getWordToDisplay(“pineapple”,guesses,’t’) returns “—e—-e”.
  • getWordToDisplay(“pineapple”,guesses,’i’) returns “-I-e—-e”.
  • getWordToDisplay(“pineapple”,guesses,’p’) returns “P–e-PP-e”.
  • getWordToDisplay(“pineapple”,guesses,’e’) returns “—E—-E”.

2e) Method to check if the word has been completely guessed

Write a method isWordGuessed() which takes as input an array of integers (representing the guesses) and returns true if all the elements are equal to 1, false otherwise.

2f ) Method to simulate a game

Write a method play() which takes an integer as input and simulates a game of “Guess the word!”. The method creates an object of type Scanner to retrieve the inputs from the user (remember that to use Scanner you should add the appropriate import statement at the beginning of your file). The method should then do the following:

  1. Generate a random secret word to be guessed using getRandomWord().
  2. Generate the corresponding array of guesses.
  3. Display a welcome message to the player letting them know how many characters the secret word has and that they have 10 lives to guess the entire word.
  4. Display a message letting the player know how many lives they have left and asking for their next guess.
  5. If the player provides a String that contains more than one character, then an error message is displayed. The player should not lose a life for doing this.
  6. If the guess is a single character, but it is not valid, then a different error message should be displayed. Once again, the player should not lose a life for doing this.
  7. If the guess is a valid, then the method checks whether it is correct or not (and the array of guesses gets updated). In both cases, a word is displayed containing the characters that the player has already guessed or hyphens otherwise. If the last guess was incorrect, the player loses 1 life.
  8. Go back to step 4 and ask for a new guess until the game is completed or until the player has lost all their lives.
  9. If the game ends because the player has guessed the word, then a congratulatory message should be displayed. Otherwise, a message letting them know that they have no lives left should be displayed and the secret word should be revealed.

Note that, to get full marks, your method must use all of the methods described above. To complete the program, simply call play() from the main method providing an integer of your choice as input. Note that the word generated depends on that integer. If you want to test your program with different words you should change the integer provided as input.

A couple of sample runs of the program are below. In both of them, play(1234) was the call made from the main method.