1. In several Game Zone assignments earlier in this book, you created games similar to Hangman in which the user guesses a secret phrase by selecting a series of letters. These versions had limited appeal because each contained only a few possible phrases to guess; after playing the games a few times, the user would have memorized all the phrases. Now create a version in which any number of secret phrases can be saved to a file before the game is played. Use a text editor such as Notepad to type any number of phrases into a file, one per line. Save the file as Phrases.txt. Then, create a game that randomly selects a phrase from the file and allows a user to guess the phrase letter by letter. Save the game as SecretPhraseUsingFile.java.

    import javax.swing.*; import java.nio.file.*; import java.io.*; import static java.nio.file.StandardOpenOption.*; public class SecretPhraseUsingFile { public static void main(String[] args) { Path file = Paths.get("C:\\Java\\Chapter.13\\Phrases.txt"); InputStream input = null; String s = ""; String displayPhrase = ""; String buildDisplayPhrase; String prompt; String play = "Play our game - guess the phrase\n"; String enterOne = "Enter one letter\n"; String sorry = "Sorry - not in the phrase: "; String correct = "Correct! "; String userResponse; char guess; char letter; boolean found = false; int position; int oldPos = 0; int x; int random = 0; int count = 0; final int LEN; x = 0; try { input = Files.newInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); s = reader.readLine(); while(s != null) { ++count; s= reader.readLine(); } random = (int) (Math.random() * 100) % count; input.close(); } catch (Exception e) { System.out.println(e); } try { input = Files.newInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); s = reader.readLine(); int numRead = 0; while(numRead < random) { ++numRead; s = reader.readLine(); } input.close(); } catch (Exception e) { System.out.println(e); } s = s.toLowerCase(); LEN = s.length(); while(x < LEN) { if(s.charAt(x) == ' ') displayPhrase = displayPhrase + ' '; else displayPhrase = displayPhrase + "*"; ++x; } prompt = play + enterOne; while(displayPhrase.indexOf('*') != -1) { userResponse = JOptionPane.showInputDialog(null, prompt + displayPhrase); userResponse = userResponse.toLowerCase(); guess = userResponse.charAt(0); found = false; for(position = 0; position < LEN; ++position) { letter = s.charAt(position); if(letter == guess) { displayPhrase = displayPhrase.substring(0, position) + guess + displayPhrase.substring(position + 1, LEN); found = true; } } if(!found) { prompt = sorry + guess + '\n'; } else { prompt = correct + enterOne; } } JOptionPane.showMessageDialog(null, "Congratulations!\nThe phrase was:\n" + s); } }
  2. In Chapter 8, you created a game named Quiz in which the user could respond to multiple-choice questions. Modify the game so that it stores the player’s highest score from any previous game in a file and displays the high score at the start of each new game. (The first time you play the game, the high score is 0.) Save the game as QuizUsingFile.java.

    import javax.swing.*; import java.nio.file.*; import java.io.*; import static java.nio.file.StandardOpenOption.*; public class QuizUsingFile { public static void main(String[] args) { Path file = Paths.get("C:\\Java\\Chapter.13\\Scores.txt"); InputStream input = null; String s = "0"; String[] questions = {"How many players on a basketball team?\nA. 5 B. 6 C. 7", "How many points for a basket?\nA. 1 B. 2 C. 3", "How many points for a free throw?\nA. 1 B. 2 C. 3", "You can earn three points when you\nA. Make any basket\n" + "B. Throw from inside the three-point line\n" + "C. Throw from outside the three-point line", "What is the name of Chicago's NBA team?\n" + "A. Bulls B. Bears C. Cubs", "Who may ask a referee about a rule interpretation?\n" + "A. Team captain\n" + "B. A player who receives a foul\n" + "C. Any player on the floor", "Suppose a shooter from team A makes a basket\n" + "in team B's basket. Who gets credit for the basket?\n" + "A. The player who made the basket\n" + "B. The last player from team B who made a basket\n" + "C. The player from team B nearest the shooter", "A basketball game starts with a\n" + "A. Jump ball\nB. Throw in from the side\n" + "C. Throw in from the end", "Bouncing a ball while walking is\n" + "A. Slobbering B. Dribbling C. Dabbling", "Taking steps with the ball without dribbling is called\n" + "\nA. Stepping B. Dunking C. Travelling"}; char[] answers = {'A', 'B', 'A', 'C', 'A', 'A', 'C', 'A', 'B', 'C' }; char ans = ' '; int x, correct = 0; int previousCorrect = 0; String entry; boolean isGood; try { input = Files.newInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); s = reader.readLine(); System.out.println(s); input.close(); } catch (IOException e) { System.out.println(e); } int score = Integer.parseInt(s); previousCorrect = score; JOptionPane.showMessageDialog(null, "The previous high score is " + score); for(x = 0; x < questions.length; ++x) { isGood = false; int firstError = 0; while(!isGood) { isGood = true; entry = JOptionPane.showInputDialog(null,questions[x]); ans = entry.charAt(0); if(ans != 'A' && ans != 'B' && ans != 'C') { isGood = false; if(firstError == 0) { questions[x] = questions[x] + "\nYour answer must be A, B or C."; firstError = 1; } } } if(ans == answers[x]) { ++correct; JOptionPane.showMessageDialog(null, "Correct!"); } else JOptionPane.showMessageDialog(null, "The correct answer is " + answers[x]); } JOptionPane.showMessageDialog(null, "You got " + correct + " right and\n" +(questions.length - correct) + " wrong"); if(correct > previousCorrect) s = "" + correct; else s = "" + previousCorrect; byte data[] = s.getBytes(); OutputStream output = null; try { output = new BufferedOutputStream(Files.newOutputStream(file, CREATE)); output.write(data); output.flush(); output.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }
  3. Use a text editor to create a comma-delimited file of user IDs and passwords. Revise any one of the games you have created throughout this book so the user must first enter a correct ID and its associated password before playing. Save the program as GameWithPassword.java.

    import javax.swing.JOptionPane; import java.nio.file.*; import java.io.*; public class GameWithPassword { public static void main(String[] args) { Path file = Paths.get("C:\\Java\\Chapter.13\\GamePlayers.txt"); String userId; String password; String s; String delim = ","; String[] array = new String[2]; boolean okToPlay = false; int guess; int result; String msg; int attempts = 1; final int LOW = 1; final int HIGH = 10; result = LOW + (int)(Math.random() * HIGH); userId = JOptionPane.showInputDialog(null, "Enter your user ID"); password = JOptionPane.showInputDialog(null, "Enter your password"); try { InputStream input = new BufferedInputStream(Files.newInputStream(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); s = reader.readLine(); while(s != null) { array = s.split(delim); if(array[0].equals(userId) && array[1].equals(password)) okToPlay = true; s = reader.readLine(); } reader.close(); } catch(Exception e) { System.out.println("Message: " + e); } if(!okToPlay) { JOptionPane.showMessageDialog(null, "Sorry - your ID or password was invalid"); } else { guess = Integer.parseInt(JOptionPane.showInputDialog(null, "Try to guess my number between " + LOW + " and " + HIGH)); while(guess != result) { if(guess < result) msg = "Your guess was too low"; else msg = "Your guess was too high"; guess = Integer.parseInt(JOptionPane.showInputDialog(null, msg + "\nGuess again")); ++attempts; } JOptionPane.showMessageDialog(null,"Correct! You got it in " + attempts + " attempts"); } } }