Hey guys i have a weird problem but its probably something small. i have a hang man program that has no errors. i am using netbeans to compile my project but when i run it it nothing come up or prints out. i don't know what im doing wrong because i have no errors:/ heres my code

Hangman class (main)

package ****;

import static java.lang.System.out;
import java.util.Scanner;

public class Hangman {

    static final boolean DEBUG = true;


    static char promptAndGetResponse(Scanner sc, String prompt) {
        prompt = "Please guess a letter---> ";

        out.println("Welcome to Hangman ...");
        out.println("\t... a program which allows you to play a hame of hanhman .");
        out.print(prompt);
         sc = new Scanner(System.in);
        String line= sc.nextLine();
        line.toLowerCase();

        return line.charAt(0);
    }

    /**
     * Play out the guessing of one word.
     */
    static void play1round(Scanner sc) {
        Word word = null;
        Word copy = null;
        Word foundSoFar = null;

        char guess;
        word = new Word();
        copy = new Word(word);
        word = new Word('-', word.length());


        if (DEBUG) {
            out.println("The word is " + word);
            out.println();
        }

        while (true) {

            out.println("So far: " + foundSoFar);
            guess = promptAndGetResponse(sc, "\nEnter guess (0 to exit) > ");
            if (guess == '0') {
                break;
            }
            if (DEBUG) {
                out.println("Your guess was " + guess);
            }
            // note: matched adds matched letter to "foundSoFar"
            //       and changes the matched letter in "copy" to '-'
            if (Word.matched(guess, foundSoFar, copy)) {
                // FOR STUDENT TO COMPLETE

                if (word.equals(foundSoFar)) {
                    out.println("Thats Right !!!!");
                    break;

                }
            }
        }
    }

    /**
     * main entry point.
     * @return  neglects to set any exit codes
     * @param args name of data file
     */
    public static void main(String[] args) throws java.io.FileNotFoundException {
        java.io.File file = new java.io.File("words.txt");
        if (!file.canRead()) {
            out.println("Can't read file words.txt");
            System.exit(1);
        }
        java.io.FileInputStream fis = new java.io.FileInputStream(file);
        java.util.Scanner sc = new java.util.Scanner(fis);
        Word.initializeWordlist(sc);
        sc.close();
        sc = new java.util.Scanner(System.in);

        char c = promptAndGetResponse(sc, "Want to guess a word? ");
        while (c == 'y') {
            play1round(sc);
            c = promptAndGetResponse(sc, "Want to guess a word? ");
        }
    }
}

And this is my word class to get the words

package *****;

import static java.lang.System.out;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;

public class Word {

    private static java.util.ArrayList<String> wordlist = null;
    private char[] lexeme = null; // the characters in the word

    /**
     * Build a list of words from file.
     * @param sc - connected to file containing word list
     * @global wordlist - this method adds content to wordlist
     */
    @SuppressWarnings("empty-statement")
    public static void initializeWordlist(Scanner sc) {
        wordlist = new java.util.ArrayList<String>();

        int i = 0;
        while (sc.hasNext());
        String word = sc.next();
        wordlist.add(word);
        i++;
    }

    /**
     * Construct a random Word object.
     * @global wordlist - copies a word from here
     */
    public Word() {


        Random random = new Random();
        int randomWord = random.nextInt(wordlist.size());
        String word = wordlist.get(randomWord);
        lexeme = new char[word.length()];

        for (int i = 0; i < lexeme.length; i++) {
            lexeme[i] = word.charAt(i);
        }
    }

    /**
     * Construct a copy of a give Word object.
     * @param word - word to copy
     */
    public Word(Word word) {

        lexeme = new char[word.length()];
        for (int i = 0; i < this.lexeme.length; i++) {
            this.lexeme[i] = word.lexeme[i];
        }
    }

    /**
     * Construct a word of a given length repeating a single character.
     * @param ch - char to repeat
     * @param length - number of times to repeat ch
     */
    public Word(char ch, int length) {
        lexeme = new char[length];
        for (int j = 0; j < lexeme.length; j++) {
            lexeme[j] = ch;
        }
    }

    public int length() {
        return lexeme.length;
    }

    public String toString() {
        return new String(lexeme);
    }

    /**
     * Search for a matched character.
     * @return:  whether "copy" contains the char denoted by "guess"
     * @param guess the user's attempt at guessing a letter
     * @param disposableCopy a copy of secret word which we can destroy
     * @param whatWeHaveSoFar the part of the word we've solved so far
     */
    public static boolean matched(char guess,
            Word whatWeHaveSoFar,
            Word disposableCopy) {
        for (int i = 0; i < disposableCopy.lexeme.length; i++) {
            if (guess == disposableCopy.lexeme[i]) {
                whatWeHaveSoFar.lexeme[i] = guess;
                disposableCopy.lexeme[i] = '-';
                return true;
            }
        }
        return false;
    }

    /**
     * Does this Word object equal another Word object?
     * @return whether or not the contents in the two lexemes equal?
     */
    public boolean equals(Word otherWord) {
       if (this.lexeme.length != otherWord.lexeme.length) {
            return false;
        }
        for (int i = 0; i < this.lexeme.length; i++) {
            if (this.lexeme[i] != otherWord.lexeme[i]) {
                return false;
            }
        }

        return true;
    }
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

i usually see it as

System.out.println();

You do

out.println();

Interesting it doesn't error. I guess its legal but perhaps the deviance is why you see nothing.

Mike

hey Mike thanks for your response i used this import

#
import static java.lang.System.out;

it import system.out so i can just use out.whatever just a little short cut but maybe i will take out the import and try it with system.out.println()

Eric :)

i ran a portion with out.println and it worked.

I can see this code as a potential problem:

if (!file.canRead()) {

out.println("Can't read file words.txt");

System.exit(1);

}

If you have a dos box open and type java to run i think your ok.

If you run through the ide which creates a dos box, I can see it flashing a dos box up and on exit making the dos box disappear. A solution is have a line read like type any key to exit then call exit.

Mike

so i added this code to my word class

while ((sc.hasNext()) && (i != wordlist.size())) {
            String word = sc.next();
            wordlist.add(word);
            i++;
        }

which gave me this output

Welcome to Hangman ...
        ... a program which allows you to play a game of hangman .
Please guess a letter---> l
BUILD SUCCESSFUL (total time: 7 seconds)

the program quits after i type a letter in. so i think i'm not storing the letters or its not even reading my text file. hmmmm back to the drawing boards

Just in case it might still exit before you see all output, you can run by going to run typing cmd to bring up a dos box.

Then, i got this the other week for how to run a package by typing in dos box:

java -cp "c:\mydocs\space invaders" org.newdawn.spacein
vaders.Game

where my package starting with the org folder is located in c:\mydocs\space invaders ( that's my class path), and i type the fully qualified name before Game.java which has my main class. I'm not clear if this is still an issue. Another possible approach if this is an issue is a readline at the end of main, so it cant exit before you type something giving you a chance to read more.

With that said and done you are going to have to get more debug output.

You don't use any trys and catches, and that might be worth looking into then again it may not be covered yet and may be to complex to include in this coding assignment at the present. I'm sure if you google java try catch tutorial it will bring up the oracle tutorial page.

Mike

my concern is the dos box or black box is being dispose as if you xed it out before you can read everything. readlns can prevent this, and opening a dos box and typing the command to run means that your dos box will never exit out on program termination.

if the dox box says c:\mydocs: <type here>

on program exit it goes back to c:\mydocs: <type here> and yuo can see whats above.

IDE's create this dos or black command box but as soon as program exits they close it as if you xed it out, unless it has to wait for a readline.

Mike

Thanks for the advice Mike :)

sooo silly me i was not prompting the program right i needed to type "y" to continue but now im getting this error

Welcome to Hangman ...
        ... a program which allows you to play a game of hangman .
Want to guess a word?...yes or no: yes
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.RangeCheck(ArrayList.java:547)
        at java.util.ArrayList.get(ArrayList.java:322)
        at csc212project05.Word.<init>(Word.java:52)
        at csc212project05.Hangman.play1round(Hangman.java:45)
        at csc212project05.Hangman.main(Hangman.java:111)
Java Result: 1
BUILD SUCCESSFUL (total time: 11 seconds)

i believe the problem is with this method

public Word() {
        // what i need to do
        // select a random word from the wordlist using the get method
        // allocate a new char array to lexeme the length of this word
        // use a for loop to copy word.charAt(i) into lexeme[i]

     
        String word = wordlist.get(0);
        lexeme = new char[word.length()];
        for (int i = 0; i < lexeme.length; i++) {
            lexeme[i] = word.charAt(i);
        }
    }

my trouble is the random word i believe im doing it wrong.
also im using netbeans to compile my code im not to familiar with the command line

Edited 5 Years Ago by Oblivious21: n/a

this comes to mind as a pottential problem

int i = 0;
while (sc.hasNext());
String word = sc.next();
wordlist.add(word);
i++;

your while loop doesnt use { } which means you loop through only one line of code.

Mike

actually maybe i don't know what that means since the while has a ; after it. It may be something you've learned that i don't know but i still see some issue here.

No your totaly right Mike

here is my new loop :

public static void initializeWordlist(Scanner sc) {
        wordlist = new java.util.ArrayList<String>();
        int i = 0;
        while ((sc.hasNext()) && (i != wordlist.size())) {
            String word = sc.next();
            wordlist.add(word);
            i++;
        }

    }

but im getting this error

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.RangeCheck(ArrayList.java:547)
        at java.util.ArrayList.get(ArrayList.java:322)
        at csc212project05.Word.<init>(Word.java:55)
        at csc212project05.Hangman.play1round(Hangman.java:45)
        at csc212project05.Hangman.main(Hangman.java:111)
Java Result: 1

what line of cod e is at at csc212project05.Word.<init>(Word.java:55). also how many words are you reading? do a print line and see how many words are in wordlist.

Mike

Hey mike
so i have played around with this some more and made progress :) :)
i have fixed the errors ( had to remove the && statnment form my while loop and redo the prompt here are my fixed classes

Hangman class (main)

package csc212project05;

import static java.lang.System.out;
import java.util.Scanner;

public class Hangman {

    static final boolean DEBUG = true;

    static char promptAndGetResponse(Scanner sc, String prompt) {
   
        out.print(prompt);

         sc = new Scanner(System.in);
        String line= sc.nextLine();
        line.toLowerCase();
        return line.charAt(0);
    }

    /**
     * Play out the guessing of one word.
     */
    static void play1round(Scanner sc) throws Exception {
        Word word = null;
        Word copy = null;
        Word foundSoFar = null;

        char guess;
        // this is what i need to do here, but something is wrong with either the
        // to top chunk or the bottom chunk
        // construct word using the default constructor Word()
        // construct a copy of word using the constructor Word(word)
        // construct a word of all '-'s using
        // the constructor Word('-', word.length())

        word = new Word();
        copy = new Word(word);
        word = new Word('-', word.length());

        if (DEBUG) {
            out.println("The word is " + word);
            out.println();
        }

        while (true) {

            out.println("So far: " + foundSoFar);
            guess = promptAndGetResponse(sc, "\nEnter guess (0 to exit) > ");
            if (guess == '0') {
                break;
            }
            if (DEBUG) {
                out.println("Your guess was " + guess);
            }
            // note: matched adds matched letter to "foundSoFar"
            //       and changes the matched letter in "copy" to '-'
            if (Word.matched(guess, foundSoFar, copy)) {
                if (word.equals(foundSoFar)) {
                    out.println("Thats Right !!!!");
                    break;
                }
            }
        }
    }

    /**
     * main entry point.
     * @return  neglects to set any exit codes
     * @param args name of data file
     */
    public static void main(String[] args) throws java.io.FileNotFoundException, Exception {
        java.io.File file = new java.io.File("words.txt");
        if (!file.canRead()) {
            out.println("Can't read file words.txt");

            System.exit(1);
        }
        java.io.FileInputStream fis = new java.io.FileInputStream(file);
        java.util.Scanner sc = new java.util.Scanner(fis);
        Word.initializeWordlist(sc);
        sc.close();
        sc = new java.util.Scanner(System.in);

        char c = promptAndGetResponse(sc, "Want to guess a word? ");
        while (c == 'y') {

        play1round(sc);
            c = promptAndGetResponse(sc, "Want to guess a word? ");
        }
    }
}

And here is my new Word class

package csc212project05;

import static java.lang.System.out;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;

public class Word {

    private static java.util.ArrayList<String> wordlist = null;
    private char[] lexeme = null; // the characters in the word

    /**
     * Build a list of words from file.
     * @param sc - connected to file containing word list
     * @global wordlist - this method adds content to wordlist
     */
    @SuppressWarnings("empty-statement")
    public static void initializeWordlist(Scanner sc) {

        wordlist = new java.util.ArrayList<String>();
        int i = 0;
        while (sc.hasNext()) {
            String word = sc.next();
            wordlist.add(word);
            i++;
        }

    }
    

    /**
     * Construct a random Word object.
     * @global wordlist - copies a word from here
     */
    public Word() throws Exception {
        if (wordlist == null) {
            throw new Exception("Word list not initialized");
        }
        int randomValue = (int) (Math.random() * wordlist.size());
        String characters = wordlist.get(randomValue);
        lexeme = new char[characters.length()];

        for (int i = 0; i < lexeme.length; i++) {
            lexeme[i] = characters.charAt(i);
        }
    }

    /**
     * Construct a copy of a give Word object.
     * @param word - word to copy
     */
    public Word(Word word) {

        lexeme = new char[word.length()];
        for (int i = 0; i < lexeme.length; i++) {
            word.lexeme[i] = lexeme[i];
        }
    }

    /**
     * Construct a word of a given length repeating a single character.
     * @param ch - char to repeat
     * @param length - number of times to repeat ch
     */
    public Word(char ch, int length) {
        lexeme = new char[length];
        for (int j = 0; j < lexeme.length; j++) {
            lexeme[j] = ch;
        }
    }

    public int length() {
        return lexeme.length;
    }

    public String toString() {
        return new String(lexeme);
    }

    /**
     * Search for a matched character.
     * @return:  whether "copy" contains the char denoted by "guess"
     * @param guess the user's attempt at guessing a letter
     * @param disposableCopy a copy of secret word which we can destroy
     * @param whatWeHaveSoFar the part of the word we've solved so far
     */
    public static boolean matched(char guess,
            Word whatWeHaveSoFar,
            Word disposableCopy) {
        for (int i = 0; i < disposableCopy.lexeme.length; i++) {
            if (guess == disposableCopy.lexeme[i]) {
                whatWeHaveSoFar.lexeme[i] = guess;
                disposableCopy.lexeme[i] = '-';
                return true;
            }
        }
        return false;
    }

    /**
     * Does this Word object equal another Word object?
     * @return whether or not the contents in the two lexemes equal?
     */
    public boolean equals(Word otherWord) {
       if (this.lexeme.length != otherWord.lexeme.length) {
            return false;
        }
        for (int i = 0; i < this.lexeme.length; i++) {
            if (this.lexeme[i] != otherWord.lexeme[i]) {
                return false;
            }
        }
        return true;
    }
}

this is my Word.txt file

medium
beyond
remain
previous
identical
distance
effort
explanation
accurate
opportunity
volume
compete
proceed
donkey
combination
moisture
awkward
meadow
manufacture
agriculture

ok now with all that is out of the way, thats my entire project :) i have a semi working hang man program. the problem is the the guess letter is not being copied into have so far.. i commented where i think the problem is in the hangman class. this is the result i am getting

run:
Want to guess a word? yes
The word is -------

So far: null

Enter guess (0 to exit) > H
Your guess was H
So far: null

Enter guess (0 to exit) > r
Your guess was r
So far: null

Enter guess (0 to exit) > l
Your guess was l
So far: null

Enter guess (0 to exit) > g
Your guess was g
So far: null

Enter guess (0 to exit) > 0
Want to guess a word? no
BUILD SUCCESSFUL (total time: 36 seconds)

You have been a great help and i am feeling good about this almost there :)
Eric

Edited 5 Years Ago by Oblivious21: n/a

The first time around you could add

if (foundSofar != null)
#
word = new Word();
#
copy = new Word(word);
#
word = new Word('-', word.length());
#

definitely an issue there

that's where i thought the problem but im not sure what to do :/ semi frustrating

This article has been dead for over six months. Start a new discussion instead.