Homework 7
1. Reversing Strings (Character Arrays) (5 points)
Create a static method called
reverse
that will reverse an array of characters. This method should take in an array of characters and should return an array of characters. The returned array will have the same length and be the reverse of the original string. The method declaration should look something like:
public static char[] reverse(char[] inChars)
You can test your method by running the following
main
method. This method should print out the word olleH on the screen if yourreverse
method is working correctly.
public static void main(String [] args)
{
char[] word = {'H','e','l','l','o'};
char[] reverseWord = reverse(word);
for (int i = 0; i < reverseWord.length; i++)
System.out.print(reverseWord[i]); // should print: olleH
System.out.println();
}
NOTE: the
main
andreverse
methods should be defined in the same class, in other words, you should have onle one file for this program.
2. Random Number Finder (10 points)
Create a program that declares and initializes an array of 10 random non-negative integers, and then asks the user for a number to check for in the array. The array should be initialized using the
Math.random()
method. The random numbers should be in the range from 0 to 20. The user should be given the option of quitting the program or entering a new number to search for in the array. If the number is in the array, then you should display the index where it is located. If the number is not in the array, the program should output "Number not found". If the user enters a negative number, then quit the program. Here is a possible run of the program:Please enter an integer between 0 and 20 to search for (neg. to quit): 5
The number 5 is not found in the array.
Please enter an integer between 0 and 20 to search for (neg. to quit):15
The number 15 is located at index 7 in the array.
Please enter an integer between 0 and 20 to search for (neg. to quit): -1
Goodbye.
3. Tic Tac Toe Extra Credit (5 points) [Savitch, Ch. 6, problem 7, page 456]
Write a class definition for a class called
TicTacToe
. An object of typeTicTacToe
is a single game of Tic Tac Toe. Store the game board as a single two-dimensional array ofchar
s with three rows and three columns. Include methods to:Write a
- add a move
- display the board
- determine whose turn it is (X or O)
- determine if there is a winner
- say who the winner is
- reinitialize (restart) the game from the beginning
main
method for the class that will allow the user(s) to play the game at the keyboard. Both players will sit at the keyboard and enter their moves in turn.