Eclipse is rejecting my public void init method - java

Eclipse SDK v3.2.1 is rejecting my public void init method.
I'm using the following imports:
import acm.graphics.*;
import acm.program.*;
import acm.util.*;
My program has a run() method and an init() method but the init() is causing these errors
- overrides acm.program.Program.init
- Cannot override the final method from Program
Note, this is not a stand-alone application yet. Just running it from the Eclipse editor.
Apparently there is a an init method in the acm.program library. How do I implement my own initization method without attempting to override the acm.program built-in one? I've tried making my init method private with private void init but then I get:
- Cannot reduce the visibility of the inherited method from Program
- Cannot override the final method from Program
Here is the code so far. The error is with the init().
public class Hangman extends GraphicsProgram {
//CONSTANTS
private static int NUMBER_OF_INCORRECT_GUESSES = 8;
//Initialize the program
public void init() { //this gives compiler a problem
HangmanCanvas canvas = new HangmanCanvas();
add(canvas);
}
public void run() {
/* When the user plays Hangman, the computer first selects a secret word at
random from a list built into the program. The program then prints out a row of dashes—one
for each letter in the secret word—and asks the user to guess a letter. If the user guesses
a letter that is in the word, the word is redisplayed with all instances of that letter
shown in the correct positions, along with any letters correctly guessed on previous turns.
If the letter does not appear in the word, the user is charged with an incorrect guess.
The user keeps guessing letters until either (1) the user has correctly guessed all the
letters in the word or (2) the user has made eight incorrect guesses. */
HangmanLexicon lexicon = new HangmanLexicon();
RandomGenerator rgen = new RandomGenerator();
int wordIndex = rgen.nextInt(0, lexicon.getWordCount()-1);
while (true) { //allows multi-play
int play = 0;
String answer = readLine ("Want to play?");
if(answer.equals("Y") || answer.equals("y") || answer.equals("yes") || answer.equals("Yes")) {play = 1;}
if(play == 0) {break;}
//Initialize some stuff
//get new random word
secretWord = lexicon.getWord(rgen.nextInt(0,wordIndex));
println("Welcome to Hangman.");
secretWord = secretWord.toUpperCase(); // convert secret word to upper case
int length = secretWord.length();
//reset game variables
String guess = "";
//clear the canvas
canvas.reset();
//reset the wrong answer count
wrong = 0;
// build the blank status word
currentWord = ""; //reset the word for multi-play
// build the dashes in status word as long as the secret word.
for (int i = 0; i < length; i++) {
currentWord += "-";
}
println("The word looks like this " + currentWord);
while (wrong<NUMBER_OF_INCORRECT_GUESSES && !currentWord.equals(secretWord)) {
guess = ".";
char g = guess.charAt(0);
while (!Character.isLetter(g)){ //if input is not a character, keep asking
guess = readLine("Guess a letter: ");
guess = guess.toUpperCase();
g = guess.charAt(0);
if (!Character.isLetter(g)){println("Your guess is not a single letter. Guess again: ");}
}
if(secretWord.indexOf(guess) < 0) {/*if guess is not in the secret word, increment wrong answer count and print message
to that effect. */
wrong++;
println("Threre are no " + guess + "\'s in the word.");
println("You have " + (NUMBER_OF_INCORRECT_GUESSES - wrong) + " guesses left.");
}
else {
println("That guess is correct.");
currentWord = wordBuild(guess);
if (currentWord.equals(secretWord)) { //if win print win but don't bother with the update to display
println("You win! You guessed the word: " + secretWord);}
else { println("The word now looks like this " + currentWord); //print the updated dash word
println("You have " + (NUMBER_OF_INCORRECT_GUESSES - wrong) + " guesses left.");
}
}
}
if(!currentWord.equals(secretWord)) {println("You lose.");} //out of guesses and word is not good.
}
}
//Build and/or update the dash word ------ displayed
public String wordBuild(String guess) {
String dashWord = "";
for (int i = 0; i < secretWord.length(); i++) {
if(secretWord.charAt(i) == guess.charAt(0)) {
dashWord = dashWord + guess;
}
else {dashWord = dashWord + currentWord.charAt(i);
}
}
return dashWord;
}
//INSTANCE VARS
int wrong = 0;
String currentWord = "";
String secretWord = "";
private HangmanCanvas canvas;
} //end of class

I suppose you are taking Stanford CS106A course and that is causing the init final issue. The problem is the Karel.jar library u must have imported during the first few lectures. I suppose that library has init() method as final and that is the root cause. So the simple solution is to remove Karel.jar from the reference library as :
In package explorer choose Reference Libraries.
Right click on Karel.jar.
Chose Build Path from the context menu.
Chose Remove from Build Path.
But in case u need to do Karel Programming again using Eclipse you'll have to import the Reference Library again from the Assignment 1 Package by follwing a similar course but choosing to import the library.
To make sure you keep on using the acm methods, please make sure to import acm.jar by downloading it from jtf.acm.org. To add libraries you make use Eclipse Documentation or just Google it.

Related

Troubled with how and where to implement if/else statements

I am almost finished creating a hangman game in Java, although I am having difficulty with one last part. I want to make it so the program checks if all the letters of the word have been guessed correctly and if so, the game prints a message saying they have won, the game ends and the program goes to the do while loop in the main class asking if they would like to play again. If not however, the game continues until this point or if all 5 guesses have been used - to which again, it is sent to the do while loop in order to restart the game and not simply terminate the program.
The problem is I am unsure how and where exactly to structure the if and else statements in order to do so.
Any help would be greatly appreciated, if I can provide further information to help narrow anything down please ask too, thank you in advance.
Instantiable Class
public class Hangman {
private char letterGuess;
private int numberLives;
private String outputWord, endMessage;
private final String hiddenWord;
private final StringBuffer swapBuffer = new StringBuffer();
public Hangman() {
letterGuess = ' ';
numberLives = 5;
hiddenWord = "java";
outputWord = "";
endMessage = "";
for (int i = 0; i < hiddenWord.length(); i++) {
swapBuffer.append("*");
}
}
public void setLetterGuess(char letterGuess) {
this.letterGuess = letterGuess;
}
public void compute() {
boolean letterFound = false;
for (int i = 0; i < hiddenWord.length(); i++) {
if (letterGuess == hiddenWord.charAt(i)) {
swapBuffer.setCharAt(i, letterGuess);
letterFound = true;
}
}
if (!letterFound) numberLives--;
outputWord = swapBuffer.toString();
}
public int getNumberLives() {
return numberLives;
}
public String getHiddenWord() {
return hiddenWord;
}
public String getOutputWord() {
return outputWord;
}
public String getEndMessage() {
return endMessage;
}
}
Main Class
import javax.swing.*;
public class HangmanApp {
public static void main(String[] args) {
char letterGuess;
int numberLives;
String hiddenWord, outputWord, endMessage, restartGame;
do {
Hangman myHangman = new Hangman();
JOptionPane.showMessageDialog(null, "Welcome to Java Hangman!");
JOptionPane.showMessageDialog(null, "In this game, a word will be printed to you in asterisks - each letter will be revealed upon a correct guess!");
JOptionPane.showMessageDialog(null, "You have 5 lives for the game, the game will end if you make too many incorrect guesses!");
for (int i = 0; i < 10; i++) {
hiddenWord = myHangman.getHiddenWord();
numberLives = myHangman.getNumberLives();
JOptionPane.showMessageDialog(null, "You currently have " +numberLives+ " lives!");
letterGuess = JOptionPane.showInputDialog(null, "Now, please enter a letter : ").charAt(0);
myHangman.setLetterGuess(letterGuess);
myHangman.compute();
outputWord = myHangman.getOutputWord();
JOptionPane.showMessageDialog(null, "The word so far is : " +outputWord);
}
numberLives = myHangman.getNumberLives();
JOptionPane.showMessageDialog(null, "You have finished the game with : " +numberLives+ " lives!");
restartGame = JOptionPane.showInputDialog(null, "Would you like to play again?");
}
while (restartGame.equalsIgnoreCase("Yes"));
}
}
Here's the way I see it. After you call myHangman.compute();, you want to check to see if the player has either won the game or run out of lives. Each of these is a separate test using an if expression. There is no else part because if the test fails, the game just goes on.
If one of these conditions is recognized, then you want to display a message, and then you want to exit the current game loop so the user will be asked if they want to play another game. The way to do this is with the break statement.
One issue you have is that you don't have a way in your main game loop to ask the Hangman class if the user has guessed the whole word. To be able to do this, you can add this method to the bottom of your Hangman class:
public boolean getAllLettersFound() {
return outputWord.indexOf('*') < 0;
}
This method checks to see if there are any * in outputWord. If not, then the user has guessed all the letters. So with this method added, the main loop can query the Hangman object to find out if the player has won.
To put this all together, you need to add the two condition checks to your main game loop, right after you call myHangman.compute();. Here are those two if blocks:
if (myHangman.getAllLettersFound()) {
JOptionPane.showMessageDialog(null, "You Won!!!!");
break;
}
if (myHangman.getNumberLives() == 0) {
JOptionPane.showMessageDialog(null, "You Ran Out Of Guesses");
break;
}
That should do it. Happy coding!

Direct code to loop a text input check until correct?

I'm trying to write a simple little text adventure, DnD-style thing here as practice, but I have run into a problem that I can't for the life of me find a solution for.
I need to create a loop for when the user types the text response incorrectly because I don't want it responding to just anything the user types in and don't want to force the user to restart the entire program. I know about the do/while loop, but I have no idea how to implement it in a text input check because everyone uses it with numbers, not text.
Here's the code:
package drake;
import java.util.*;
public class drake {
public static void main(String[]args) {
Random rand = new Random();
Scanner kb = new Scanner(System.in);
int ini_d = rand.nextInt((17 - 12) + 1) + 12;
int ini_u = rand.nextInt((20 - 1) + 1) + 1;
int cha_d = 16;
int cha_u = 15;
int r_d = rand.nextInt((20 - 11) + 1) + 11;
int r_u = rand.nextInt((20 - 1) + 1) + 1;
int hp_d = 50;
int hp_u = 30;
int dam_d = rand.nextInt((12 - 7) + 1) + 7;
int dam_u = rand.nextInt((17 - 12) + 1) + 12;
System.out.println("A young dragon towers over you, it's reptilian eyes digging into your very soul. It roars at you, posing a challenge.");
System.out.println("Type 'roll' to roll for initiative.");
String u_r1 = kb.next();
while(true)
if (u_r1.equalsIgnoreCase ("roll")) {
System.out.println(ini_d);
System.out.println(ini_u);
break;
}
else {
System.out.println("Your input was invald. Please try again.");
//I need to give the user another chance to input text, and then direct the program to check it again and again until it's typed in correctly.
return;
}
if (ini_d >= ini_u) {
System.out.println("The dragon rushes towards you in an attempt to attack you.");
}
}
}
Move String u_r1 = kb.next(); as the first statement in the while loop should work for you (since you break on encountering the right input).
while(true) {
String u_r1 = kb.next();
if (u_r1.equalsIgnoreCase("roll")) {
System.out.println(ini_d);
System.out.println(ini_u);
break;
} else {
System.out.println("Your input was invald. Please try again.");
}
}
//Rest of the code

How do you, using a set of random given letters, check if a word is created with only those given letters

In Java, I am supposed to make a word game where one is supposed to make letters with a given set of random letters. I have already wrote the code to find the letters (Variable is String Letters ), but I am having trouble checking if the word chosen by the player (String word), is actually created using the given letters? I have a txt file of all the English words in the English language, and this is what I am basing it off if it is a word. How do I do this? I am pretty sure it has something to do with checking the index, or using the built in command contains at.
I have already tried to search for this. However other questions used C-Language or Python. I have found 1 Java explanation, however I am new to coding and do not understand the code and variables they used.
This is an example of where I need help
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
Full method.
public static void getWord(String letters) {
int trys = 0;
int trysLeft = 5;
System.out.println("Input a word that you can make with those letters");
while (trys < 5) {
String word = getString(); //getString is a method where user can input a desired string
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
}
else if (Words.contains(word) == false) {
System.out.println("That is not a real word! Please enter a word that you can make with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
else if (Words.contains(letters) == false) {
System.out.println("You can not make a word with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
}
}
You need to check the cointains for each letter. If you send a charSeq, example { 'a' , 'b', 'd' }, java will try to find if your string contains completely "abd"
One way to do it is to sort the letters in your letter list and your word and see if your word is contains in the available letters, like this:
public static void main(String args[]) {
String letters = sort("haat");
System.out.println("Is a word: " + letters.contains(sort("hat")));
}
public static String sort(String s)
{
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
There are many techniques that you could use to implement this class project.
Here is one:
Build a Map from the input letters. The key of the map should be a Character and the Value of the map should be the count of letters.
Build a Map from the word guess. Again, the key of the map should be a Character and the Value of the map should be the count of letters.
Compare the maps. If they are equal, then the word is constructed from exactly the letters in the input letters string.

Hangman Game Not Reading From File

This program is supposed to pick a random word from a .txt file and have the user try and guess the letters to the word. It runs, but it always says "letter was not found in word" even when I know it's a letter that all of the words have. This makes me think that it isn't properly reading my .txt file.
package hangman;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Hangman{
public static void main(String[] args) {
ArrayList<String> dictionaryList = new ArrayList<>();
File file = new File("src/hangman.txt");
try {
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
dictionaryList.add(line);
}
}
} catch (FileNotFoundException e) {
}
/*
* Getting the word and hiding it
*/
Random rng = new Random();
int word = rng.nextInt(dictionaryList.size()); //randomly chooses a word from the text file
Scanner scanner = new Scanner(System.in);
int guessesLeft = 6; // the total amount of guesses the user gets
ArrayList<Character> alreadyGuess = new ArrayList<>(); // keep tracks of the user's guesses
boolean wordFound = false; // keeps track of when the game will end after the user runs out of guesses
String wordSelected = dictionaryList.get(word); //converts the int value of the randomly choose word to a string
char[] letters = wordSelected.toCharArray(); // converts the word to a char
char[] hideWord = new char[letters.length]; // gets the length of hiding the word
// the for loop hides the word by replacing it with '_'
for(int i = 0; i < letters.length; i++) {
hideWord[i]='_';
}
/*
* Starts the hangman game. The while loop will keep running the game.
*/
while(true){
//for testing purposes they can use the print statement below to replace the other print statement
//System.out.print("\n" + wordSelected + "\n" + "Word: ");
System.out.print("\n" + "Word: ");
for(int i = 0; i < letters.length; i++){
System.out.print(hideWord[i]);
} // Display the word
// Allows user to input and displays the guesses that are left
System.out.print("\n" + "Guesses Left: " + guessesLeft +"\nAlready Guess: " + alreadyGuess + "\nGuess: ");
char userInput = scanner.nextLine().toUpperCase().charAt(0); // uppercase the String first, and then pick the char
// Checks to see if the user already guess the same word
for(int i = 0; i < alreadyGuess.size(); i++){
if(userInput==alreadyGuess.get(i)){
System.out.println("\nYou already guessed this letter. Try Again. ");
break;
}
}
// records the user's guesses
if(!(alreadyGuess.contains(userInput))){
alreadyGuess.add(userInput);
}
// Checks if the user guesses the right letter in the word
for(int i = 0; i < letters.length; i++) {
if(userInput==letters[i]) {
hideWord[i] = userInput;
wordFound = true;
}
}
// If user guesses the incorrect letter it will display this and lower the amount of guesses
if(!wordFound){
System.out.println("\nThe letter was not found in the word. \n");
guessesLeft = 1;
}
wordFound = false; // resets the wordFound boolean back to false
// if user runs out of guesses left, they will lose.
if(guessesLeft<=0){
System.out.println("\nYou lose, you hanged the man.");
break;
}
// if user guesses correctly on the word, they win. Uses the array class to compare two char arrays
if(Arrays.equals(letters,hideWord)){
System.out.println("\nWord: " + wordSelected);
System.out.println("\nCongratulations! You guess the right word and save the man from being hang.");
break;
}
}
}
}
Never, ever, ever catch and ignore exceptions! Change the catch clause at the top of the program like this:
catch (FileNotFoundException e) {
e.printStackTrace();
}
so that you will at least have a hint if something bad happened while you were trying to read your word list.
This is such an important lesson it bears repeating, in bold type: Never, ever, ever catch and ignore exceptions!

How to prompt a user for additional input for a Java Hangman game?

I have an assignment for a beginner Java course that has asked me to create a class called Hangman. The program is supposed to prompt a user (player one) to input a String, then print dashes on the screen for each character in the screen. The program then asks a second user (player two) to take guesses one character at a time until either the word has been guessed, or they have six failed attempts. As each correct guess is verified, the corresponding dash in the string is replaced with the correct letter.
At this point I have created code that will scan in a user String, and replace the String with dashes. The code also prompts the second user for a comparison letter. The code will also replace the first correct guess in the dash String.
The problem I have at this point is that I can't seem to find a way to prompt the user for additional input after the first guess. The program will accept the first correct guess, replace it, and then terminate. I removed a portion of code that checked how many incorrect / correct guesses had been input, because at this point the code would run through constantly incrementing the count and terminate the program. Any help with this problem would be greatly appreciated.
Update:
I have reworked my code to remove unwanted / unnecessary branches. Here is my updated code. At this point, I am receiving too many incorrect guesses. The code is counting every iteration through the array that does not match as incorrect. I appreciate any help you can offer.
public class Hangman
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
String word;
String letter = "";
boolean gameOver = false;
int correct = 0;
int incorrect = 0;
int index = 0;
Scanner userIn = new Scanner(System.in);
System.out.print("Player 1 enter a word: ");
word = userIn.nextLine();
String[] wordArray = word.split("");
int wordLength = word.length();
String[] wrong = {};
String[] right = {};
String[] dashes = new String[wordLength];
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
for(int i = 0; i < wordLength; i++)
{
dashes[i] = "-";
}
for(int i= 0; i < wordLength; i++)
{
System.out.print(dashes[i] +" ");
}
System.out.println();
while(incorrect < 6)
{
System.out.print("Player 2 enter a letter: ");
letter = userIn.nextLine();
letter = letter.toLowerCase();
if(letter.length() > 1)
{
System.out.println("ERROR: You have entered more than one letter.");
System.out.print("Player 2 enter a letter: ");
letter = userIn.nextLine();
}
for(int i = 0; i < wordLength; i++)
{
if( wordArray[i].equals(letter))
{
dashes[i] = letter;
System.out.println("Correct!");
for( i= 0; i < wordLength; i++)
{
System.out.print(dashes[i] +" ");
}
correct++;
}
else
{
incorrect++;
}
}
}
if(correct == wordLength)
{
System.out.println();
System.out.println("You Win!!");
System.out.println();
}
if(incorrect == 6)
{
System.out.println("You Lose.");
System.out.println("The word was " +word);
System.out.println();
}
}
}
So, that's a hefty amount of code. And I see some interesting decisions all over the place. So since you're learning I'll help you help yourself.
Before taking on an application like this you should think about your logic first (psuedo-code) before actually coding. So for a hangman game you probably want something like:
player 1 enters phrase
while wrong_guesses < max_incorrect:
prompt player 2 for a letter
check the phrase for that letter
if found
replace dashes with the letter
else
wrong_guesses++
print status message
Just glancing at your code I can see multiple places where you're asking for new input. This means you are not effectively using your loops. Your application has a lot of unnecessary branches and cleaning it up will help you debug. As an exercise, you can walk through your code and write its' psuedo-code, then compare it to mine.
Good luck!
Update:
With respect to the new and much improved code, your check loop is wrong. It should look more like this:
boolean found = false;
for(int i = 0; i < wordLength; i++)
{
if( wordArray[i].equals(letter))
{
found = true;
// replace dashes, and you don't need to loop here,
// do it after the check for better efficiency
}
}
//Outside of the loop
if (!found)
{
incorrect++;
}
//Print the current status here then
Also, your check for only 1 letter can be subverted (enter aa, then aa again). That block should be:
if(letter.length() > 1)
{
System.out.println("ERROR: You have entered more than one letter.");
System.out.print("Player 2 enter a letter: ");
//letter = userIn.nextLine();
continue; //This tells java to restart the loop
}

Categories