QUESTION 2: CLASSES
Write the complete HiddenWord class, including any necessary instance variables, its constructor, and the method, getHint, described above. You may assume that the length of the guess is the same as the length of the hidden word.
import java.util.Scanner;
public class HiddenWord {
private String word;
public HiddenWord(String hWord) {
word = hWord;
}
public String getHint(String guess) {
String hint = "";
for (int i = 0; i < guess.length(); i++) {
if (guess.substring(i, i + 1).equals(word.substring(i, i + 1))) {
hint += guess.substring(i, i + 1);
} else if (word.indexOf(guess.substring(i, i + 1)) != -1) {
hint += "+";
} else {
hint += "*";
}
}
return hint;
}
public static void main(String[] args) {
HiddenWord puzzle = new HiddenWord("HARPS");
Scanner scanner = new Scanner(System.in);
System.out.println("LETS PLAY THE GAME..");
System.out.println("GUESS THE HIDDEN WORD. (all caps, 5 letters):");
boolean guessedCorrectly = false;
while (!guessedCorrectly) {
System.out.print("Enter your guess: ");
String guess = scanner.nextLine();
String hint = puzzle.getHint(guess);
System.out.println("Hint: " + hint);
if (hint.equals(puzzle.word)) {
System.out.println("CONGRATS! You've guessed the word!");
guessedCorrectly = true;
} else {
System.out.println("WRONG, TRY AGAIN!");
}
}
scanner.close();
}
}
HiddenWord.main(null);
LETS PLAY THE GAME..
GUESS THE HIDDEN WORD. (all caps, 5 letters):
Enter your guess: Hint: H*++*
WRONG, TRY AGAIN!
Enter your guess: Hint: HA+*S
WRONG, TRY AGAIN!
Enter your guess: Hint: HARPS
CONGRATS! You've guessed the word!
This FRQ simply involved creating a Java class with all the necessary components - the main method, constructors, instance variables, all encompassing in one class that the FRQ asked to create. The mainly tricky part of the FRQ was to create the conditional statements to produce either an asterisk or a plus sign based on the guess - I struggled a bit with this and had to reference the internet to figure out how to add three conditional statements.
package com.nighthawk.spring_portfolio.nbapredictor.monte_carlo;
public class Player {
private String name;
private PlayerStats stats;
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PlayerStats getStats() {
return stats;
}
public void setStats(PlayerStats stats) {
this.stats = stats;
}
}
Throughout our project, we had a lot of implementations of basic Java classes - the above was one. This was the Player.java file, where we initialized the getters and setters for the player object. The anatomy of the class was simple - it was a public class, with private instance variables, along with setters and getters.