Loops, Arrays, and ArrayLists

Here are a variety of activities that you can do involving loops, arrays, and ArrayLists. They are roughly in order of difficulty, but they are completely independent of each other. If you're new to Java or AP, consider starting with the first one. If you've done these sorts of things before and want more of a challenge, consider the third one.

  1. Write a program to print out to the screen a list of all the prime numbers from 2 to 1000. Remember that a prime number is a number that doesn't have any integers that evenly divide into it except for 1 and itself. For example, 11 is prime because 1 divides evenly into 11, and 11 divides evenly into 11, but 2, 3, 4, 5, 6, 7, 8, 9, and 10 all do not divide evenly into 11. Alternatively, 15 is not prime because both 3 and 5 divide evenly into it. You might find the modulo operator (%) useful.
  2. Write a program to open up a file of text, and count the number of times each word appears. In order to do this, use an ArrayList of Strings to store each word that you see as you read it from the file, and use a similar ArrayList of integers to keep track of how many times you have seen that word. A better but more abstract approach (do this after you get the above working, or start here if you like) is to create a class which has two instance variables: word and count. Then you only need one ArrayList which consists of objects from this class.
  3. Implement the game of tic-tac-toe. Use a two-dimensional array to store the game board, where each location can be X, O, or empty. Make sure each move is legal (that spot hasn't already been played), and test each time to see if a win has happened or if a draw has happened. Make your program so that you can automatically adjust the size of your game: if you wanted your game to be a 5x5 grid, you should be able to change just one value (a 3 to a 5 somewhere) and everything else should just "work". You should avoid duplication of code as much as possible. For example, you shouldn't have separate code that tests rows, columns, and diagonals; instead, you should have one piece of code that does any of the above inside a method and is controlled via parameters. If you can get this working and want a further push, go to a game of 3D tic-tac-toe (ask and I can provide details). Print out the board after each round to the terminal window or graphically.

Good luck, and have fun!