Troubled with how and where to implement if/else statements - java

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!

Related

Accessing each value in array in a random order

I am making a guessing game where you are supposed to guess the capital of x country, the user is supposed to be prompted each time if they want to guess again there is an array of 15 CountryCards which I need to read through in a random order, I also cannot use the same card twice. When I run my current code I get through 14 iterations of the array and then the last one just gets stuck on the very start of the while loop (after inputting 1 into yesNo nothing happens) Here is the relevant code, any help is appreciated:
while (CountryCard.instances < 30) {
System.out.println("Would you like to guess the capital of a country?"
+ " Hit 1 for yes, or 2 for no (Case sensitive)");
yesNo = input.nextInt();
if (yesNo == 2) {
return;
}
Random generator = new Random();
int randomNumber = generator.nextInt(game.length);
while (game[randomNumber].used == true && CountryCard.uses < 15) {
randomNumber = generator.nextInt(game.length);
}
System.out.println("What is the Capital of "
+ game[randomNumber].getName() + "?");
game[randomNumber].usedCard(1);
guess = input.next();
if (guess.equals(game[randomNumber].getCapital())) {
System.out.println("Correct! :)");
} else {
System.out.println("Incorrect! :(");
}
}//end of while
System.out.println("Thanks for playing :)");
Why not just shuffle your CountryCard list in place with Collections.shuffle each time you play the game?
Something like:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
class Game {
private static final List<CountryCard> countryCards = new ArrayList<>(
Arrays.asList(
new CountryCard("Canada", "Ottawa"),
new CountryCard("USA", "Washington, D.C."),
new CountryCard("France", "Paris"),
new CountryCard("Germany", "Berlin"),
new CountryCard("Spain", "Madrid"),
new CountryCard("Turkey", "Ankara"),
new CountryCard("Sudan", "Khartoum"),
new CountryCard("Brazil", "Brasilia")
// TODO add more countries as needed
));
private Scanner input = new Scanner(System.in);
public void play() {
// shuffle the country card list before playing
Collections.shuffle(countryCards);
for (CountryCard randomCountryCard: countryCards) {
System.out.println("What is the capital of " + randomCountryCard.getName() + "?");
String guess = input.next();
if (randomCountryCard.getCapital().equalsIgnoreCase(guess)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
System.out.println("Answer: " + randomCountryCard.getCapital() + "\n");
}
}
public static void main(String[] args) {
Game game = new Game();
game.play();
}
}
class CountryCard {
private String name;
private String capital;
CountryCard(String name, String capital) {
this.name = name;
this.capital = capital;
}
public String getName() {
return name;
}
public String getCapital() {
return capital;
}
}
If your collection/array has only 15 elements you can just use Collections.shuffle() and then iterate it.
If you don't want to change the initial array you can generate the collection with indexes (from zero to array.length) and then shuffle it.
I previously mentioned in a comment that because you are randomly generating numbers in a while loop while looking for the last 1/15 number, it is very difficult to do. What you could do is implement open addressing collision handling. Of this, you can utilise either linear probing or double hashing.
Linear probing:
if random generated number is x, x is already used, instead of generating new random num, take x+1. If x+1 is used, take x+2 and so on.
double hashing:
if random generated number x is not used, continue as normal, but if it is used, utilise a hash to add a variable constant value to your x.
If it works only 14 times, then issue will be in the loop condition.
Try changing CountryCard.uses<15 to CountryCard.uses<=15
Also check the value of game.length

Java Scramble Game Input after Hint

I'm modifying an unscramble game in Java. I have two arrays: one for the original words and another for their hints. So when the user guesses incorrectly, the corresponding hint shows up and what I want is for the user to have another chance to guess after the hint is shown. But right now, I can't seem to get that 'another chance' to work. Can someone pls help? Thank you.
Code:
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
import java.util.Calendar;
import java.util.Date;
// How to create a Jumble word game in Java
public class MyProgram {
private static final String[] WORDS_DATABASE = new String[] {
"code","kids","baby", "dosa", "beach","house","apple", "paper",
"Java", "school", "science", "Oracle", "Disney", "cricket", "carrot",
"vada"
};
private static String[] hints = new String[] {
"Programs are made of ___", "Synonym for children", "Synonym for infant",
"Idli, vada, and ___", "This place is next to ocean", "Other word for 'home'",
"This is a red color fruit", "pencil and ____", "programming language",
"place for education", "Physics, chemistry, biology are all ____",
"Larry Ellison founded this company", "the ____ princesses", "Famous sport with bat and ball",
"What rabbits eat", "idli and ___"
};
public static void main(String[] args) {
MyProgram jg = new MyProgram();
jg.startGame();
}
/**
* Run a game of Jumble in Java. The steps in the game are,
* 1. Get a random word from the words database
* 2. Shuffle/jumble the word by randomly shuffling characters
* 3. Present the jumbled word to the user and ask him to guess the word.
* 4. Repeat the guess till answer is found or user decides to quit.
*/
private void startGame() {
// int numberOfGuesses = 0;
// String original = selectRandomWord();
//String shuffled = getShuffledWord(original);
boolean gameOn = true;
while(gameOn) {
int numberOfGuesses = 0;
String original = selectRandomWord();
String shuffled = getShuffledWord(original);
System.out.println("Shuffled word is: "+shuffled);
numberOfGuesses++;
String userGuess = getUserGuess();
if(original.equalsIgnoreCase(userGuess)) {
System.out.println("Congratulations! You found the word in "+numberOfGuesses+" guesses");
System.out.println("");
//gameOn = false;
}else {
System.out.println("Sorry, Wrong answer");
System.out.println("--------");
if (numberOfGuesses > 0){
displayHint(original);
System.out.println("");
// String userGuess = getUserGuess();
}
}
}
}
/**
* Get the user's word guess from command line
* #return
*/
public String getUserGuess() {
Scanner sn = new Scanner(System.in);
System.out.println("Please type in the original word: ");
return sn.nextLine();
}
/**
* Select a random word from the WORDS_DATABASE array.
* #return
*/
public String selectRandomWord() {
int rPos = ThreadLocalRandom.current().nextInt(0, WORDS_DATABASE.length);
return WORDS_DATABASE[rPos];
}
/**
* Shuffle the original word by randomly swapping characters 10 times
* #param original
* #return
*/
public String getShuffledWord(String original) {
String shuffledWord = original; // start with original
int wordSize = original.length();
int shuffleCount = 10; // let us randomly shuffle letters 10 times
for(int i=0;i<shuffleCount;i++) {
//swap letters in two indexes
int position1 = ThreadLocalRandom.current().nextInt(0, wordSize);
int position2 = ThreadLocalRandom.current().nextInt(0, wordSize);
shuffledWord = swapCharacters(shuffledWord,position1,position2);
}
return shuffledWord;
}
/**
* Swaps characters in a string using the given character positions
* #param shuffledWord
* #param position1
* #param position2
* #return
*/
private String swapCharacters(String shuffledWord, int position1, int position2) {
char[] charArray = shuffledWord.toCharArray();
// Replace with a "swap" function, if desired:
char temp = charArray[position1];
charArray[position1] = charArray[position2];
charArray[position2] = temp;
return new String(charArray);
}
private void displayHint(String s){
for (int i = 0; i < WORDS_DATABASE.length; i++){
if (WORDS_DATABASE[i].equals(s)){
System.out.println("HINT:" + hints[i]);
}
}
}
}
Add a loop at startGame() for playing again with new word like:
boolean playAgain = true;
while(playAgain)
playAgain = jg.startGame();
Modify the startGame() to return true when the user wants to play again otherwise false. Also, move the random word selection and word shuffling statements outside of the gameOn loop to stop getting new word even when the user gives the right answer.
private boolean startGame() {
boolean gameOn = true;
int numberOfGuesses = 0;
String original = selectRandomWord();
String shuffled = getShuffledWord(original);
System.out.println("Shuffled word is: "+shuffled);
while(gameOn) {
numberOfGuesses++;
String userGuess = getUserGuess();
if(original.equalsIgnoreCase(userGuess)) {
System.out.println("Congratulations! You found the word in "+numberOfGuesses+" guesses");
System.out.println("");
gameOn = false;
}else {
System.out.println("Sorry, Wrong answer");
System.out.println("--------");
if (numberOfGuesses > 0){
displayHint(original);
System.out.println("");
}
}
}
if(checkIfUserwantsToPlayAgain())
return true; // To restart the game
return false; // To stop the game
}
So when the user guesses incorrectly, the corresponding hint shows up
and what I want is for the user to have another chance to guess after
the hint is shown. But right now, I can't seem to get that 'another
chance' to work.
You just need to move the selection and scrambling of the word to BEFORE the while loop so that it doesn't pick a new word when they guess wrong. Also, why did you comment out the gameOn = false; line? That is necessary to allow the game to end.
After you move the initialization lines to before the while loop, you can now place that entire thing inside another while loop that asks the user if they want to play a new game (I'll leave that to you, though).
int numberOfGuesses = 0;
String original = selectRandomWord();
String shuffled = getShuffledWord(original);
while(gameOn) {
System.out.println("Shuffled word is: "+shuffled);
numberOfGuesses++;
String userGuess = getUserGuess();
if(original.equalsIgnoreCase(userGuess)) {
System.out.println("Congratulations! You found the word in "+numberOfGuesses+" guesses");
System.out.println("");
gameOn = false;
}else {
System.out.println("Sorry, Wrong answer");
System.out.println("--------");
if (numberOfGuesses > 0){
displayHint(original);
System.out.println("");
}
}
}
Now, when the user guesses incorrectly, it will display the hint and go back to the top of the while loop where it will ask the user for another guess. It will stay in the loop until they get it correct and gameOn is toggled to false.
But how do I make it so that the user gets to input whether they want
to play on or not, after the round ends?
You could change your main() to something like this:
public static void main(String[] args) {
boolean keepPlaying = true;
Scanner sn = new Scanner(System.in);
while (keepPlaying) {
MyProgram jg = new MyProgram();
jg.startGame();
System.out.print("Would you like to play again? [Y or YES]: ");
String response = sn.nextLine().toUpperCase();
keepPlaying = (response.equals("Y") || (response.equals("YES")));
}
}

How to program a dice race

I'm taking a programming II class in which we've been working on programming classes. Now we've been assigned homework to write a driver class to incorporate these classes. The homework states
Using the die, dice, and player classes completed in class, write a
driver class to have three players taking turns rolling the dice.
First player to accumulate a total score of 35 or more is the winner."
For example, if player 1 rolls a 3, their score is 3. Then player 2
rolls. Then player 3. As each player rolls, their roll is added to
their previous score.
I've started writing it, but have been given the error that several items in my program cannot be resolved to a type. I also have absolutely no idea how to even begin creating a loop to do what is being asked. This is what I have so far:
import java.util.Scanner;
public class DiceRace {
public static void main(String[] args){
Player player1;
Player player2;
Player player3;
Dice dice;
Scanner keyboard;
keyboard=new Scanner(System.in);
dice=new Dice();
System.out.print("First player's name: ");
player1=keyboard.next();
System.out.print("Second player's name: ");
player2=keyboard.next();
System.out.print("Third player's name: ");
player3=keyboard.next();
}//Ending bracket of method main
}//Ending bracket of class DiceRace
You can create 3 methods, for each player, and a method that plays the game. In each player's method, it first calls the play method with a parameter containing the player name, and the play method prints it out so that the player knows who's turn it is. once the play method is done, it will call the next player method, then the player after that, and finally back to player 1.
It looks like you're a beginner. You should do some tutorials or stuff like that to know the basics :) Also, if you start getting familiar with an IDE (like Eclipse) then programming will be far more easy for you as IDEs can give you detailed descriptions of errors, even while writing the code.
In your above example you need to create two classes by yourself Dice and Player, as they are not in Java by default.
The method keyboard.next() reads an input from the console and returns it as object of the type String, not Player. Thus, you can not assign the variable player1 the result, a String.
What you probably want is a Player object having a member variable String name. Here's an example:
public final class Player {
private String mName;
public Player(final String name) {
mName = name;
}
public String getName() {
return mName;
}
}
Then you can do something like this in your main-method:
player1 = new Player(keyboard.next());
System.out.println("Name of player1 is: " + player1.getName());
Next you probably want a Dice to have a roll method:
public final class Dice() {
private Random mRandom;
public Dice() {
mRandom = new Random();
}
public int roll() {
// Returns a random number between 1 and 6 (inclusive)
return mRandom.nextInt(6) + 1;
}
}
Then, in your main you can do:
Dice dice = new Dice();
System.out.println("Let's roll the dice: " dice.roll());
Now to the games logic, let's keep it very simple, beginner friendly:
int player1Score = 0;
int player2Score = 0;
int player3Score = 0;
boolean finished = false;
boolean player1One = false;
boolean player2One = false;
boolean player3One = false;
// 0 is first player, 1 second and 2 third
int currentPlayer = 0;
while(!finished) {
int rollValue = dice.roll();
if (currentPlayer == 0) {
player1Score += rollValue;
} else if (currentPlayer == 1) {
player2Score += rollValue;
} else {
player3Score += rollValue;
}
player1One = player1Score >= 35;
player2One = player2Score >= 35;
player3One = player3Score >= 35;
finished = player1One || player2One || player3One;
// Increment and modulo 3 (numbers between 0 and 2)
currentPlayer = ((currentPlayer + 1) % 3);
}
Good luck :)

Java homework hangman [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So for a class we are having to make a hangman game that can take a user input for a word and then have another person solve for it. It has to be able to recognize multiple repeating letters in the word or I would be done. Below is my code, it works great until I remove the break statement in my checkformatch method so that it goes past the initial finding of a letter. With the break in there it never finds the second third etc repeated letters, without it, it returns that each letter that is not the letter searched is a miss and reduces my life count. What I'm needing is some hints on how to search my array for the letter that is inputted as a guess and return their index positions in the array without it thinking each character in the array that is not the one guessed is a wrong input. Thank you in advance.
package hangman;
import java.util.Scanner;
class Game {
int livesRemaining;
String letterGuessed;
String wordInput;
char[] hiddenWord;
char[] aOfWord ;
Scanner input = new Scanner(System.in);
boolean isFound;
int a;
public Game()
{
this.setLives(8);
//this.output();
System.out.println("Player 1 please enter the word to be searched: ");
wordInput = input.nextLine();
aOfWord = wordInput.toCharArray();
hiddenWord = new char[aOfWord.length];
for(int j = 0; j < hiddenWord.length; j++)
hiddenWord[j] = '*';
this.output();
while(livesRemaining > 0)
{
System.out.println("Please choose a letter: ");
letterGuessed = input.nextLine();
this.checkForMatch(letterGuessed);
if(isFound == true)
{
hiddenWord[a] = letterGuessed.charAt(0);
}
else
{
System.out.println("Is not found!");
this.reduceLives();
}
this.output();
}
}
public void setLives(int a)
{
this.livesRemaining = a;
}
public void reduceLives()
{
livesRemaining = livesRemaining -1;
System.out.println("Lives remaining: " + this.getLives());
}
public int getLives()
{
return livesRemaining;
}
public void output()
{
System.out.println("Lives remaining: " + this.getLives());
System.out.println("Word found so far ");
for(int i = 0; i < hiddenWord.length; i++)
{
System.out.print(hiddenWord[i] + "\n");
}
}
public void checkForMatch(String l)
{
for(int i = 0; i < aOfWord.length; i++)
{
//System.out.println("Comparing " + l.charAt(0) + " To " + aOfWord[i]);
if(l.charAt(0) == aOfWord[i])
{
isFound = true;
a = i;
break;
}
else
{
isFound = false;
}
}
}
}
To start with, if you want to return the indices of the chars, you'll need to add them somewhere, I would recommend returning an ArrayList which would hold all of your values. This is because an ArrayList can grow in size if it is too small and you'll not really need to worry about an out of bounds issue.
Your current form of checkForMatch works for what you want, but consider returning a boolean instead of setting your isFound field to true/false. Also there is a contains method that the String class has which you can call, so an alternative to your checkForMatch would be possible sort of like
String yourString = "Hello";
String yourChar = "e";
System.out.println(yourString.contains(yourChar));
Which of course would print true!
Now, to get the indices, you already traverse the array and compare characters in your checkForMatch() method, why not simply create an ArrayList<Integer> matchedIndices = new ArrayList<Integer>(); at the top of your method, and instead of setting isFound to true, call matchedIndices.add(i); if the characters match, and then at the end return the ArrayList?
You would of course have to swap your return type from void to ArrayList, but there are many ways to go about this, this being just the first that came to my head!
Your algorithm seems fine. However, it will only get you the last matching character because a will be rewritten whenever he finds a matching character.
I think a really simple solution would be to do this in your checkForMatch method:
if(l.charAt(0) == aOfWord[i])
{
isFound = true;
hiddenWord[i] = l.charAt(0);
}
and also this in your game method...
if(!isFound)
{
System.out.println("Is not found!");
this.reduceLives();
}
You don't have to use this. by the way. That is only necessary in certain cases. Take a look at this.

Eclipse is rejecting my public void init method

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.

Categories