Hangman Help!!

hi everyone, im trying to make a hangman program but i have a few iissues first, whenever i ttry to run it, i get an "Exception in thread "main" java.lang.NoSuchMethodError: main" error and i dont know why. secondly,i dont know how to finish the metho replaceLetter. Please help!!!
--Confused Student
import java.util.*;
import java.io.*;
import java.lang.Math;
public class Hangman
private ArrayList<String> wordList;
private String word;
private String guess;
private boolean done = false;
private int numGuess = 0;
public final int MAX_GUESSES = 6;
public final String fileName = "words.txt";
public static void main(String[] args)
  * Creates the Hangman object.
  * Initializes wordList by getting the words from fileName.
  * Initializes word by choosing a word from wordList.
  * Initializes guess as an empty string.
public Hangman() throws FileNotFoundException
   wordList = getWords(fileName);
   word = chooseWord(wordList);
   guess = setEmptyString(word.length());
  * Determines if the game is done or still playing.
  * Returns true if it is won or lost.
  * Returns false otherwise.
  public boolean done()
           if (numGuess >=6)
               return true;
           return false;
  * Determines if the game has been won by guessing the word.
  * One way of determining this is if guess no longer has any "-" .
public boolean won()
  /** Add code here **/
  return false;
  * Determines if the game has been lost.
  * The game is lost if numGuess is MAX_GUESSES
public boolean lost()
            if (numGuess>=MAX_GUESS)
               return true;
            return false;
  * Determines whether the s contains letter.
public boolean has(String s, String letter)
          if (s.indexOf(letter) != -1)
               return true;
       return false;
  * Replaces the letter at index i in s with letter.
  * Does not change s.
  * Returns the new String.
public String replaceLetter(String s, int i, String letter)
  return "";
  * Replaces letter in word with "-"
  * Replaces the corresponding letter in guess with letter.
  * It must account for every instance of letter.
public void addToGuess(String letter)
     Scanner sc = new Scanner(System.in);
     String s = "";
     for(int i = 0; i < word.length(); i++)
          s += "-";
     for(int i = 0; i < word.length(); i++)
  * Prompts the user for a letter.
  * Determines if the word has the letter.
  * If it does, it must add that letter to the guess.
  * Otherwise, it must update the number of incorrect guesses.
  * It then displays the number of guess taken and the number remaining.
public void getGuess()
  System.out.println(guess + "\n");
  System.out.println("Guess a letter");
  Scanner sc = new Scanner(System.in);
  String letter = sc.next().substring(0,1);
  /** Add code here **/
  System.out.println(numGuess + " guesses.");
  System.out.println(MAX_GUESSES - numGuess + " guesses remaining.\n");
  * Returns a string of length size.
  * The string will contain only "-" characters.
public String setEmptyString(int size)
  String empty = "";
  for(int i = 0; i < size; i++)
   empty += "-";
  return empty;
  * Chooses a word from the ArrayList.
  * Returns the chosen word as a String.
  * The word is chosen at random.
public String chooseWord(ArrayList<String> list)
  int index = (int)
  (Math.random()*list.size());
  return list.get(index);
  * Gets a list of words from the given file.
  * Returns the list as an ArrayList of Strings.
public ArrayList<String> getWords(String fileName) throws
FileNotFoundException
  Scanner file = new Scanner(new File(fileName));
  ArrayList<String> words = new ArrayList<String>();
  while(file.hasNextLine())
   words.add(file.nextLine());
  return words;
  * Repeatedly calls getGuess until the game is done.
  * When the game is done, it displays an appropriate message.
public void playGame()
       while(!done())
       getGuess();
     if (won())
          System.out.println("You won!");
     else
          System.out.println("Sorry, you lose.");
/**Ralph Jones Jr**/

In your main() method, first create an object of your class Hangman and invoke methods on it. Something link this...
try{
       new Hangman().getGuess();
  }catch(FileNotFoundException f){System.out.println(f);}Since Hangman() constructor throws FileNotFoundException, you need try-catch for creating your Hangman object.

Similar Messages

  • Help with a hangman class with Gui

    Gah, so I'm creating a Java Hangman program using a gui program. Everything was working fine till I started adding the program to the gui. I'm hopelessly confused, and I can't seem to get it working. Help appreciated! Thanks guys... I'm really bad at this, sorry for the noob question.
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.io.File;
    import java.util.Random;
    import java.util.Scanner;
    import javax.accessibility.AccessibleContext;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.plaf.PanelUI;
    public class hmg extends JPanel {
         private char[] word;
         private int Misses;
         private int myWordIndex;
         private int index;
         private boolean[] used;
         protected Image[] i = new Image[8];
         protected Image[] s = new Image[3];
         private final static char NADA = '_';
         private final static int GUESSES = 8;
         private String fileName;
              i[0] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang1.jpg");
              i[1] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang2.jpg");
              i[2] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang3.jpg");
              i[3] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hange4.jpg");
              i[4] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang5.jpg");
              i[5] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang6.jpg");
              i[6] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang7.jpg");
              i[7] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang8.jpg");
              s[0] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
              s[1] = Toolkit.getDefaultToolkit().getImage(
              "C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
              s[2] = Toolkit.getDefaultToolkit().getImage(
              "C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
         protected int x = 0;
         protected ImageIcon icon = new ImageIcon(i[x++]);
         protected ImageIcon icon2 = new ImageIcon(s[x++]);
         private JLabel j = new JLabel(icon);
         private JButton b = new JButton();
         private JLabel a = new JLabel();
         private String[] wordArray;
         private String wordChosen;
         public void paintComponent(Graphics g) {
              super.paintComponents(g);
         public hmg() {
              this.add(j);
              JButton guess = new JButton("The Click of Faith!");
              this.add(guess, BorderLayout.WEST);
              guess.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if (!(x == i.length)) {
                             icon = new ImageIcon(i[x++]);
                             j.setIcon(icon);
              JButton guess2 = new JButton("Click here if your almost dead! ");
              this.add(guess2, BorderLayout.WEST);
              guess2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        icon2 = new ImageIcon(s[x++]);
                        j.setIcon(icon);
              this.add(a, BorderLayout.SOUTH);
              a.setText(showWord());
              a.setText(play());
              Misses = 0;
              index = 0;
              used = new boolean[Character.MAX_VALUE];
         //     public void actionPerformed(ActionEvent arg0) {
         //          if (!(x == i.length)) {
         //          icon = new ImageIcon(i[x++]);
         //          j.setIcon(icon);
         private void clear() {
              int k;
              for (k = 0; k < Character.MAX_VALUE; k++) {
                   used[k] = false;
              word = new char[myWords[myWordIndex].length()];
              for (k = 0; k < word.length; k++) {
                   word[k] = NADA;
         private void guess(char ch) {
              int b;
              boolean charFound = false;
              ch = Character.toLowerCase(ch);
              for (b = 0; b < word.length; b++) {
                   if (!used[ch] && myWords[index].charAt(b) == ch) {
                        word[b] = ch;
                        charFound = true;
              if (!used[ch] && !charFound) {
                   Misses++;
              used[ch] = true;
         private void chooseRandomWord()
         // myWords[];
    //     loadFileList();
              Random generator = new Random();
              int x = generator.nextInt(wordArray.length);
              wordChosen = wordArray[x];
         //public void processFile(String commonWords) {
         //     wordArray = commonWords.split(",");
         //private String[] loadFileList() {
         //     try
         //          fileName = "C:\\Documents and Settings\\mfleming\\Desktop\\Wordlist";
         //               File file = new File("C:\\Documents and
         // Settings\\mfleming\\Desktop\\Wordlist");
         //          if(file.exists());
         //               Scanner scan = new Scanner(file);
         //               while(scan.hasNext())
         //                    String word = scan.next();
         //                    processFile(word);
         //     } catch (Exception e)
         //          e.printStackTrace();
         //     return wordArray;
         //     public void add() {
         //          try {
         //               Scanner s = new Scanner(new File("Wordlist"));
         //               while (s.hasNext())
         //          } catch (Exception e) {
         private String showWord() {
              int k;     
              String temp = "";
              for (k = 0; k < word.length; k++) {
                   temp +=word[k];
    //               System.out.print(word[k] + " ");
              return temp;
              //                    return showWord();
    //          System.out.println(" \nYou have exactly " + (GUESSES - Misses)
    //                    + " guesses left! Time is running out! Cue Music LOL ");
         private boolean wordGuessed() {
              int a;
              for (a = 0; a < word.length; a++) {
                   if (word[a] == NADA) {
                        return false;
              return true;
         // .setIcon --- Put image.
         public String play() {
              clear();
              String temp = "";
              while (true) {
    //               showWord();
                   a.setText(showWord());
                   //May not have to return string.
    //               System.out
    //                         .print("Your guess shall be? 1234567890abcdefhijklmnopqrstuvqxyz hA! Guess... it's simply up to you!");
                   String s = Blah.readString();
                   if (s.length() > 0) {
                        guess(s.charAt(0));
                   if (Misses >= GUESSES) {
    //                    System.out.println("You killed your hangman because....");
                        //                    System.out.println(storeWord);
                        break;
                   } else if (wordGuessed()) {
    //                    System.out.println("You win. You suck. LOL. ><");
    //                    System.out.println(word);
                        break;
              index = (index + 1) / myWords.length;
              return temp;
         //     public String storeWord() {
         //          return SW;
         public static final void main(String args[]) {
              hmg hmg = new hmg();
              hmg.play();
         private class MousePressedListener implements MouseListener {
              public void mousePressed(MouseEvent e) {
                   if (e.getButton() == e.BUTTON1) {
                        ((JButton) e.getSource()).setText("X");
                   if (e.getButton() == e.BUTTON3) {
                        ((JButton) e.getSource()).setText("O");
              * (non-Javadoc)
              * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
              public void mouseClicked(MouseEvent arg0) {
                   // TODO Auto-generated method stub
              * (non-Javadoc)
              * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
              public void mouseEntered(MouseEvent arg0) {
                   // TODO Auto-generated method stub
              * (non-Javadoc)
              * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
              public void mouseExited(MouseEvent arg0) {
                   // TODO Auto-generated method stub
              * (non-Javadoc)
              * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
              public void mouseReleased(MouseEvent arg0) {
                   // TODO Auto-generated method stub
         * (non-Javadoc)
         * @see java.awt.Component#getAccessibleContext()
         public AccessibleContext getAccessibleContext() {
              // TODO Auto-generated method stub
              return super.getAccessibleContext();
         * (non-Javadoc)
         * @see javax.swing.JPanel#getUI()
         public PanelUI getUI() {
              // TODO Auto-generated method stub
              return super.getUI();
         * (non-Javadoc)
         * @see javax.swing.JComponent#getUIClassID()
         public String getUIClassID() {
              // TODO Auto-generated method stub
              return super.getUIClassID();
         * (non-Javadoc)
         * @see java.awt.Component#paramString()
         protected String paramString() {
              // TODO Auto-generated method stub
              return super.paramString();
         * (non-Javadoc)
         * @see javax.swing.JPanel#setUI(javax.swing.plaf.PanelUI)
         public void setUI(PanelUI arg0) {
              // TODO Auto-generated method stub
              super.setUI(arg0);
         * (non-Javadoc)
         * @see javax.swing.JComponent#updateUI()
         public void updateUI() {
              // TODO Auto-generated method stub
              super.updateUI();
         private String myWords[] = { "analysis", "approach", "area", "assessment",
                   "assume", "authority     ", "available", "benefit ", "concept ",
                   "consistent", "constitutional", "context", "contract", "create",
                   "data", "definition", "derived ", "distribution ", "economic",
                   "environment ", "established", "estimate ", "evidence", "export",
                   "factors", "financial", "formula", "function", "identified",
                   "income", "indicate ", "individual ", "interpretation",
                   "involved", "issues", "labour", "legal", "legislation", "major ",
                   "method", "occur", "percent ", "period", "policy", "principle",
                   "procedure", "process", "required", "research", "response", "role",
                   "section", "sector", "significant ", "similar", "source",
                   "specific", "structure", "theory", "variables", "achieve ",
                   "acquisition", "administration ", "affect", "appropriate ",
                   "aspects", "assistance ", "categories", "chapter", "commission",
                   "community", "complex ", "computer ", "conclusion", "conduct",
                   "consequences", "construction", "consumer ", "credit", "cultural ",
                   "design", "distinction", "elements ", "equation", "evaluation ",
                   "features ", "final", "focus", "impact", "injury", "institute ",
                   "investment", "items", "journal ", "maintenance", "normal",
                   "obtained ", "participation", "perceived ", "positive ",
                   "potential", "previous", "primary ", "purchase ", "range ",
                   "region", "regulations", "relevant ", "resident", "resources",
                   "restricted ", "security ", "sought", "select", "site",
                   "strategies", "survey", "text", "traditional", "transfer",
                   "alternative", "circumstances ", "comments", "compensation",
                   "components", "consent", "considerable", "constant ",
                   "constraints", "contribution", "convention ", "coordination",
                   "core", "corporate ", "corresponding", "criteria", "deduction",
                   "demonstrate ", "document", "dominant", "emphasis ", "ensure",
                   "excluded", "framework ", "funds", "illustrated ", "immigration",
                   "implies", "initial ", "instance ", "interaction", "justification",
                   "layer", "link", "location", "maximum ", "minorities", "negative ",
                   "outcomes", "partnership", "philosophy ", "physical ",
                   "proportion ", "published ", "reaction", "registered ", "reliance",
                   "removed", "scheme", "sequence", "sex", "shift", "specified ",
                   "sufficient", "task", "technical ", "techniques", "technology",
                   "validity", "volume", "access", "adequate", "annual", "apparent",
                   "approximated", "attitudes ", "attributed ", "civil", "code",
                   "commitment ", "communication", "concentration", "conference ",
                   "contrast ", "cycle", "debate", "despite ", "dimensions ",
                   "domestic ", "emerged ", "error", "ethnic", "goals", "granted",
                   "hence", "hypothesis ", "implementation", "implications",
                   "imposed", "integration", "internal ", "investigation", "job",
                   "label", "mechanism ", "obvious", "occupational ", "option",
                   "output", "overall ", "parallel", "parameters", "phase",
                   "predicted", "principal", "prior", "professional", "project",
                   "promote", "regime", "resolution ", "retained", "series",
                   "statistics ", "status", "stress", "subsequent", "sum", "summary",
                   "undertaken ", "academic ", "adjustment ", "alter ", "amendment ",
                   "aware ", "capacity ", "challenge ", "clause ", "compounds ",
                   "conflict ", "consultation ", "contact ", "decline ",
                   "discretion ", "draft ", "enable ", "energy ", "enforcement ",
                   "entities ", "equivalent ", "evolution ", "expansion ",
                   "exposure ", "external ", "facilitate ", "fundamental ",
                   "generated ", "generation ", "image ", "liberal", "licence ",
                   "logic ", "marginal ", "medical ", "mental ", "modified ",
                   "monitoring ", "network ", "notion ", "objective ", "orientation ",
                   "perspective ", "precise ", "prime ", "psychology ", "pursue ",
                   "ratio ", "rejected ", "revenue ", "stability ", "styles ",
                   "substitution ", "sustainable", "symbolic ", "target ",
                   "transition ", "trend ", "version ", "welfare ", "whereas ",
                   "abstract ", "accurate ", "acknowledged ", "aggregate ",
                   "allocation ", "assigned ", "attached ", "author ", "bond ",
                   "brief ", "capable ", "cited ", "cooperative ", "discrimination ",
                   "display ", "diversity ", "domain ", "edition ", "enhanced ",
                   "estate ", "exceed ", "expert ", "explicit ", "federal ", "fees ",
                   "flexibility ", "furthermore ", "gender ", "ignored ",
                   "incentive ", "incidence ", "incorporated ", "index ",
                   "inhibition ", "initiatives ", "input ", "instructions ",
                   "intelligence ", "interval ", "lecture ", "migration ", "minimum ",
                   "ministry ", "motivation ", "neutral ", "nevertheless ",
                   "overseas ", "preceding ", "presumption ", "rational ",
                   "recovery ", "revealed ", "scope ", "subsidiary ", "tapes ",
                   "trace ", "transformation ", "transport ", "underlying ",
                   "utility ", "adaptation ", "adults ", "advocate ", "aid ",
                   "channel ", "chemical", "classical ", "comprehensive ",
                   "comprise ", "confirmed ", "contrary ", "converted ", "couple ",
                   "decades ", "definite", "deny ", "differentiation ", "disposal ",
                   "dynamic ", "eliminate ", "empirical ", "equipment ", "extract ",
                   "file ", "finite ", "foundation ", "global ", "grade ",
                   "guarantee ", "hierarchical ", "identical ", "ideology ",
                   "inferred ", "innovation ", "insert ", "intervention ",
                   "isolated ", "media ", "mode ", "paradigm ", "phenomenon ",
                   "priority ", "prohibited ", "publication ", "quotation ",
                   "release ", "reverse ", "simulation ", "solely ", "somewhat ",
                   "submitted ", "successive ", "survive ", "thesis ", "topic ",
                   "transmission ", "ultimately ", "unique ", "visible ",
                   "voluntary ", "abandon ", "accompanied ", "accumulation ",
                   "ambiguous ", "appendix ", "appreciation ", "arbitrary ",
                   "automatically ", "bias ", "chart ", "clarity", "conformity ",
                   "commodity ", "complement ", "contemporary ", "contradiction ",
                   "crucial ", "currency ", "denote ", "detected ", "deviation ",
                   "displacement ", "dramatic ", "eventually ", "exhibit ",
                   "exploitation ", "fluctuations ", "guidelines ", "highlighted ",
                   "implicit ", "induced ", "inevitably ", "infrastructure ",
                   "inspection ", "intensity ", "manipulation ", "minimised ",
                   "nuclear ", "offset ", "paragraph ", "plus ", "practitioners ",
                   "predominantly ", "prospect ", "radical ", "random ",
                   "reinforced ", "restore ", "revision ", "schedule ", "tension ",
                   "termination ", "theme ", "thereby ", "uniform ", "vehicle ",
                   "via ", "virtually ", "widespread ", "visual ", "accommodation ",
                   "analogous ", "anticipated ", "assurance ", "attained ", "behalf ",
                   "bulk ", "ceases ", "coherence ", "coincide ", "commenced ",
                   "incompatible ", "concurrent ", "confined ", "controversy ",
                   "conversely ", "device ", "devoted ", "diminished ", "distorted",
                   "distortion", "equal", "figures", "duration ", "erosion ",
                   "ethical ", "format ", "founded ", "inherent ", "insights ",
                   "integral ", "intermediate ", "manual ", "mature ", "mediation ",
                   "medium ", "military ", "minimal ", "mutual ", "norms ",
                   "overlap ", "passive ", "portion ", "preliminary ", "protocol ",
                   "qualitative ", "refine ", "relaxed ", "restraints ",
                   "revolution ", "rigid ", "route ", "scenario ", "sphere ",
                   "subordinate ", "supplementary ", "suspended ", "team ",
                   "temporary ", "trigger ", "unified ", "violation ", "vision ",
                   "adjacent ", "albeit ", "assembly ", "collapse ", "colleagues ",
                   "compiled ", "conceived ", "convinced ", "depression ",
                   "encountered ", "enormous ", "forthcoming ", "inclination ",
                   "integrity ", "intrinsic ", "invoked ", "levy ", "likewise ",
                   "nonetheless ", "notwithstanding ", "odd ", "ongoing ", "panel ",
                   "persistent ", "posed ", "reluctant ", "straightforward ",
                   "undergo ", "whereby ", "noob", "frag", "punish", "lamer", "noobs",
                   "knife", "shank", "humvee", "sniper", "don't", "run", "you'll",
                   "only", "die", "tired", "LOL", "ROFL", "GG", "FTW", "indeed",
                   "sure", "yeah", "yea", "hi", "hello", };
    DRIVER CLASS
    import java.awt.BorderLayout;
    import java.awt.Container;
    import javax.swing.JFrame;
    public class HangManGuiTest {
         public static void main(String[] args) {
    //          hangmangui hmg = new hangmangui();
              hmg hmg = new hmg();
              JFrame frame = new JFrame("Hangman! DJ Joker[8]Baller");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(hmg);
              frame.pack();
              frame.show();
    //          JFrame j = new JFrame();
    //          Listeners - Control everything - Call stuff from hmg.
    //          frame.getContentPane().add(hmg);
    //          j.setSize(500, 500);
    //          j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //          j.setVisible(true);
              hmg.play();
    Message was edited by:
    joker8baller

    Hey! Thanks for the tip...
    Anyways, I fixed all of the errors (T hank god) and now all I have t o do is add the text to the gui. Help for adding the text into the gui. When I run it, it runs a gui, and it shows the spaces, but when I put in input.. nothing shows up and nothing plays.
    So I'm going to use a.setText... for showWord and and play()... Is there anything else I woiuld need to do?
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.io.File;
    import java.util.Random;
    import java.util.Scanner;
    import javax.accessibility.AccessibleContext;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.plaf.PanelUI;
    public class hmg extends JPanel {
         private char[] word;
         private int Misses;
         private int myWordIndex;
         private int index;
         private boolean[] used;
         protected Image[] i = new Image[8];
         protected Image[] s = new Image[3];
         private final static char NADA = '_';
         private final static int GUESSES = 8;
         private String fileName;
              i[0] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang1.jpg");
              i[1] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang2.jpg");
              i[2] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang3.jpg");
              i[3] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hange4.jpg");
              i[4] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang5.jpg");
              i[5] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang6.jpg");
              i[6] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang7.jpg");
              i[7] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hang8.jpg");
              s[0] = Toolkit.getDefaultToolkit().getImage(
                        "C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
              s[1] = Toolkit.getDefaultToolkit().getImage(
              "C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
              s[2] = Toolkit.getDefaultToolkit().getImage(
              "C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
         protected int x = 0;
         protected ImageIcon icon = new ImageIcon(i[x++]);
         protected ImageIcon icon2 = new ImageIcon(s[x++]);
         private JLabel j = new JLabel(icon);
         private JButton b = new JButton();
         private JLabel a = new JLabel();
         private String[] wordArray;
         private String wordChosen;
         public void paintComponent(Graphics g) {
              super.paintComponents(g);
         public hmg() {
              this.add(j);
              JButton guess = new JButton("The Click of Faith!");
              this.add(guess, BorderLayout.WEST);
              guess.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if (!(x == i.length)) {
                             icon = new ImageIcon(i[x++]);
                             j.setIcon(icon);
              JButton guess2 = new JButton("Click here if your almost dead! ");
              this.add(guess2, BorderLayout.WEST);
              guess2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        icon2 = new ImageIcon(s[x++]);
                        j.setIcon(icon);
    //          this.add(a, BorderLayout.SOUTH);
    //          a.setText(clear());
    //          a.setText(showWord());
    //          a.setText(play());
              Misses = 0;
              index = 0;
              used = new boolean[Character.MAX_VALUE];
         //     public void actionPerformed(ActionEvent arg0) {
         //          if (!(x == i.length)) {
         //          icon = new ImageIcon(i[x++]);
         //          j.setIcon(icon);
         private void clear() {
              int k;
              for (k = 0; k < Character.MAX_VALUE; k++) {
                   used[k] = false;
              word = new char[myWords[myWordIndex].length()];
              System.out.println(word.length);
              for (k = 0; k < word.length; k++) {
                   word[k] = NADA;
         private void guess(char ch) {
              int b;
              boolean charFound = false;
              ch = Character.toLowerCase(ch);
              for (b = 0; b < word.length; b++) {
                   if (!used[ch] && myWords[index].charAt(b) == ch) {
                        word[b] = ch;
                        charFound = true;
              if (!used[ch] && !charFound) {
                   Misses++;
              used[ch] = true;
         private void chooseRandomWord()
         // myWords[];
    //      loadFileList();
              Random generator = new Random();
              int x = generator.nextInt(wordArray.length);
              wordChosen = wordArray[x];
         //public void processFile(String commonWords) {
         //     wordArray = commonWords.split(",");
         //private String[] loadFileList() {
         //     try
         //          fileName = "C:\\Documents and Settings\\mfleming\\Desktop\\Wordlist";
         //               File file = new File("C:\\Documents and
         // Settings\\mfleming\\Desktop\\Wordlist");
         //          if(file.exists());
         //               Scanner scan = new Scanner(file);
         //               while(scan.hasNext())
         //                    String word = scan.next();
         //                    processFile(word);
         //     } catch (Exception e)
         //          e.printStackTrace();
         //     return wordArray;
         //     public void add() {
         //          try {
         //               Scanner s = new Scanner(new File("Wordlist"));
         //               while (s.hasNext())
         //          } catch (Exception e) {
         private String showWord() {
              int k;     
              String temp = "";
              for (k = 0; k < word.length; k++) {
                   temp +=word[k];
    //               System.out.print(word[k] + " ");
              return temp;
              //                    return showWord();
    //          System.out.println(" \nYou have exactly " + (GUESSES - Misses)
    //                    + " guesses left! Time is running out! Cue Music LOL ");
         private boolean wordGuessed() {
              int a;
              for (a = 0; a < word.length; a++) {
                   if (word[a] == NADA) {
                        return false;
              return true;
         // .setIcon --- Put image.
         public String play() {
              clear();
              String temp = "";
              while (true) {
    //               showWord();
                   a.setText(showWord());
                   //May not have to return string.
         JOptionPane.showInputDialog("Your guess shall be? 1234567890abcdefhijklmnopqrstuvqxyz hA! Guess... its simply up to you!");
    //               System.out
    //                         .print("Your guess shall be? 1234567890abcdefhijklmnopqrstuvqxyz hA! Guess... it's simply up to you!");
                   String s = Blah.readString();
                   if (s.length() > 0) {
                        guess(s.charAt(0));
                   if (Misses >= GUESSES) {
                        JOptionPane.showMessageDialog(null,"You killed your hangman because....");
    //                    System.out.println("You killed your hangman because....");
                        //                    System.out.println(storeWord);
                        break;
                   } else if (wordGuessed()) {
                        JOptionPane.showMessageDialog(null, "You win. You suck. LOL. ><");
    //                    System.out.println("You win. You suck. LOL. ><");
    //                    System.out.println(word);
                        break;
              index = (index + 1) / myWords.length;
              return temp;
         //     public String storeWord() {
         //          return SW;
         public static final void main(String args[]) {
              hmg hmg = new hmg();
              hmg.play();
               * (non-Javadoc)
               * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
              public void mouseClicked(MouseEvent arg0) {
                   // TODO Auto-generated method stub
               * (non-Javadoc)
               * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
              public void mouseEntered(MouseEvent arg0) {
                   // TODO Auto-generated method stub
               * (non-Javadoc)
               * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
              public void mouseExited(MouseEvent arg0) {
                   // TODO Auto-generated method stub
               * (non-Javadoc)
               * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
              public void mouseReleased(MouseEvent arg0) {
                   // TODO Auto-generated method stub
          * (non-Javadoc)
          * @see java.awt.Component#getAccessibleContext()
         public AccessibleContext getAccessibleContext() {
              // TODO Auto-generated method stub
              return super.getAccessibleContext();
          * (non-Javadoc)
          * @see javax.swing.JPanel#getUI()
         public PanelUI getUI() {
              // TODO Auto-generated method stub
              return super.getUI();
          * (non-Javadoc)
          * @see javax.swing.JComponent#getUIClassID()
         public String getUIClassID() {
              // TODO Auto-generated method stub
              return super.getUIClassID();
          * (non-Javadoc)
          * @see java.awt.Component#paramString()
         protected String paramString() {
              // TODO Auto-generated method stub
              return super.paramString();
          * (non-Javadoc)
          * @see javax.swing.JPanel#setUI(javax.swing.plaf.PanelUI)
         public void setUI(PanelUI arg0) {
              // TODO Auto-generated method stub
              super.setUI(arg0);
          * (non-Javadoc)
          * @see javax.swing.JComponent#updateUI()
         public void updateUI() {
              // TODO Auto-generated method stub
              super.updateUI();
         private String myWords[] = { "approach", "area", "assessment",
                   "assume", "authority     ", "available", "benefit ", "concept ",
                   "consistent", "constitutional", "context", "contract", "create",
                   "data", "definition", "derived ", "distribution ", "economic",
                   "environment ", "established", "estimate ", "evidence", "export",
                   "factors", "financial", "formula", "function", "identified",
                   "income", "indicate ", "individual  ", "interpretation",
                   "involved", "issues", "labour", "legal", "legislation", "major ",
                   "method", "occur", "percent ", "period", "policy", "principle",
                   "procedure", "process", "required", "research", "response", "role",
                   "section", "sector", "significant  ", "similar", "source",
                   "specific", "structure", "theory", "variables", "achieve ",
                   "acquisition", "administration  ", "affect", "appropriate ",
                   "aspects", "assistance ", "categories", "chapter", "commission",
                   "community", "complex ", "computer ", "conclusion", "conduct",
                   "consequences", "construction", "consumer ", "credit", "cultural ",
                   "design", "distinction", "elements ", "equation", "evaluation ",
                   "features ", "final", "focus", "impact", "injury", "institute ",
                   "investment", "items", "journal ", "maintenance", "normal",
                   "obtained ", "participation", "perceived ", "positive ",
                   "potential", "previous", "primary ", "purchase ", "range ",
                   "region", "regulations", "relevant ", "resident", "resources",
                   "restricted ", "security ", "sought", "select", "site",
                   "strategies", "survey", "text", "traditional", "transfer",
                   "alternative", "circumstances ", "comments", "compensation",
                   "components", "consent", "considerable", "constant ",
                   "constraints", "contribution", "convention ", "coordination",
                   "core", "corporate ", "corresponding", "criteria", "deduction",
                   "demonstrate ", "document", "dominant", "emphasis ", "ensure",
                   "excluded", "framework ", "funds", "illustrated ", "immigration",
                   "implies", "initial ", "instance ", "interaction", "justification",
                   "layer", "link", "location", "maximum ", "minorities", "negative ",
                   "outcomes", "partnership", "philosophy ", "physical ",
                   "proportion ", "published ", "reaction", "registered ", "reliance",
                   "removed", "scheme", "sequence", "sex", "shift", "specified ",
                   "sufficient", "task", "technical ", "techniques", "technology",
                   "validity", "volume", "access", "adequate", "annual", "apparent",
                   "approximated", "attitudes ", "attributed ", "civil", "code",
                   "commitment ", "communication", "concentration", "conference ",
                   "contrast ", "cycle", "debate", "despite ", "dimensions ",
                   "domestic ", "emerged ", "error", "ethnic", "goals", "granted",
                   "hence", "hypothesis ", "implementation", "implications",
                   "imposed", "integration", "internal ", "investigation", "job",
                   "label", "mechanism ", "obvious", "occupational ", "option",
                   "output", "overall ", "parallel", "parameters", "phase",
                   "predicted", "principal", "prior", "professional", "project",
                   "promote", "regime", "resolution ", "retained", "series",
                   "statistics ", "status", "stress", "subsequent", "sum", "summary",
                   "undertaken ", "academic ", "adjustment ", "alter ", "amendment ",
                   "aware ", "capacity ", "challenge ", "clause ", "compounds ",
                   "conflict ", "consultation ", "contact ", "decline ",
                   "discretion ", "draft ", "enable ", "energy ", "enforcement ",
                   "entities ", "equivalent ", "evolution ", "expansion ",
                   "exposure ", "external ", "facilitate ", "fundamental ",
                   "generated ", "generation ", "image ", "liberal", "licence ",
                   "logic ", "marginal ", "medical ", "mental ", "modified ",
                   "monitoring ", "network ", "notion ", "objective ", "orientation ",
                   "perspective ", "precise ", "prime ", "psychology ", "pursue ",
                   "ratio ", "rejected ", "revenue ", "stability ", "styles ",
                   "substitution ", "sustainable", "symbolic ", "target ",
                   "transition ", "trend ", "version ", "welfare ", "whereas ",
                   "abstract ", "accurate ", "acknowledged ", "aggregate ",
                   "allocation ", "assigned ", "attached ", "author ", "bond ",
                   "brief ", "capable ", "cited ", "cooperative ", "discrimination ",
                   "display ", "diversity ", "domain ", "edition ", "enhanced ",
                   "estate ", "exceed ", "expert ", "explicit ", "federal ", "fees ",
                   "flexibility ", "furthermore ", "gender ", "ignored ",
                   "incentive ", "incidence ", "incorporated ", "index ",
                   "inhibition ", "initiatives ", "input ", "instructions ",
                   "intelligence ", "interval ", "lecture ", "migration ", "minimum ",
                   "ministry ", "motivation ", "neutral ", "nevertheless ",
                   "overseas ", "preceding ", "presumption ", "rational ",
                   "recovery ", "revealed ", "scope ", "subsidiary ", "tapes ",
                   "trace ", "transformation ", "transport ", "underlying ",
                   "utility ", "adaptation ", "adults ", "advocate ", "aid ",
                   "channel ", "chemical", "classical ", "comprehensive ",
                   "comprise ", "confirmed ", "contrary ", "converted ", "couple ",
                   "decades ", "definite", "deny ", "differentiation ", "disposal ",
                   "dynamic ", "eliminate ", "empirical ", "equipment ", "extract ",
                   "file ", "finite ", "foundation ", "global ", "grade ",
                   "guarantee ", "hierarchical ", "identical ", "ideology ",
                   "inferred ", "innovation ", "insert ", "intervention ",
                   "isolated ", "media ", "mode ", "paradigm ", "phenomenon ",
                   "priority ", "prohibited ", "publication ", "quotation ",
                   "release ", "reverse ", "simulation ", "solely ", "somewhat ",
                   "submitted ", "successive ", "survive ", "thesis ", "topic ",
                   "transmission ", "ultimately ", "unique ", "visible ",
                   "voluntary ", "abandon ", "accompanied ", "accumulation ",
                   "ambiguous ", "appendix ", "appreciation ", "arbitrary ",
                   "automatically ", "bias ", "chart ", "clarity", "conformity ",
                   "commodity ", "complement ", "contemporary ", "contradiction ",
                   "crucial ", "currency ", "denote ", "detected ", "deviation ",
                   "displacement ", "dramatic ", "eventually ", "exhibit ",
                   "exploitation ", "fluctuations ", "guidelines ", "highlighted ",
                   "implicit ", "induced ", "inevitably ", "infrastructure ",
                   "inspection ", "intensity ", "manipulation ", "minimised ",
                   "nuclear ", "offset ", "paragraph ", "plus ", "practitioners ",
                   "predominantly ", "prospect ", "radical ", "random ",
                   "reinforced ", "restore ", "revision ", "schedule ", "tension ",
                   "termination ", "theme ", "thereby ", "uniform ", "vehicle ",
                   "via ", "virtually ", "widespread ", "visual ", "accommodation ",
                   "analogous ", "anticipated ", "assurance ", "attained ", "behalf ",
                   "bulk ", "ceases ", "coherence ", "coincide ", "commenced ",
                   "incompatible ", "concurrent ", "confined ", "controversy ",
                   "conversely ", "device ", "devoted ", "diminished ", "distorted",
                   "distortion", "equal", "figures", "duration ", "erosion ",
                   "ethical ", "format ", "founded ", "inherent ", "insights ",
                   "integral ", "intermediate ", "manual ", "mature ", "mediation ",
                   "medium ", "military ", "minimal ", "mutual ", "norms ",
                   "overlap ", "passive ", "portion ", "preliminary ", "protocol ",
                   "qualitative ", "refine ", "relaxed ", "restraints ",
                   "revolution ", "rigid ", "route ", "scenario ", "sphere ",
                   "subordinate ", "supplementary ", "suspended ", "team ",
                   "temporary ", "trigger ", "unified ", "violation ", "vision ",
                   "adjacent ", "albeit ", "assembly ", "collapse ", "colleagues ",
                   "compiled ", "conceived ", "convinced ", "depression ",
                   "encountered ", "enormous ", "forthcoming ", "inclination ",
                   "integrity ", "intrinsic ", "invoked ", "levy ", "likewise ",
                   "nonetheless ", "notwithstanding ", "odd ", "ongoing ", "panel ",
                   "persistent ", "posed ", "reluctant ", "straightforward ",
                   "undergo ", "whereby ", "noob", "frag", "punish", "lamer", "noobs",
                   "knife", "shank", "humvee", "sniper", "don't", "run", "you'll",
                   "only", "die", "tired", "LOL", "ROFL", "GG", "FTW", "indeed",
                   "sure", "yeah", "yea", "hi", "hello", };
    }Message was edited by:
    joker8baller

  • I need help with my hangman project

    I'm working on a project where we are developing a text based version of the game hangman. For every project we add a new piece to the game. Well for my project i have to test for a loser and winner for the game and take away a piece of the game when the user guesses incorrectly. these are the instrcutions given by my professor:
    This semester we will develop a text based version of the Game Hangman. In each project we will add a new a piece to the game. In project 4 you will declare the 'figure', 'disp', and 'soln' arrays to be attributes of the class P4. However do not create the space for the arrays until main (declaration and creation on separate lines). If the user enters an incorrect guess, remove a piece of the figure, starting with the right leg (looking at the figure on the screen, the backslash is the right leg) and following this order: the left leg (forward slash), the right arm (the dash or minus sign), the left arm (the dash or minus sign), the body (vertical bar), and finally the head (capital O).
    Not only will you need to check for a winner, but now you will also check to see if all the parts of the figure have been removed, checking to see if the user has lost. If the user has lost, print an error message and end the program. You are required to complete the following operations using for loops:
    intializing appropriate (possible) variables, testing to see if the user has guessed the correct solution, testing to see if the user has guessed a correct letter in the solution, and determining / removing the next appropriate part of the figure. All other parts of the program will work as before.
    Declare figure, disp, and soln arrays as attributes of the class
    Creation of the arrays will remain inside of main
    Delete figure parts
    Check for loss (all parts removed)
    Implement for loops
    Init of appropriate arrays
    Test for winner
    Test if guess is part of the solution
    Removal of correct position from figure
    Output must be
    C:\jdk1.3.1\bin>java P3
    |
    |
    O
    -|-
    Enter a letter: t
    |
    |
    O
    -|-
    t _ _ t
    Enter a letter: a
    |
    |
    O
    -|-
    t _ _ t
    Enter a letter: e
    |
    |
    O
    -|-
    t e _ t
    Enter a letter: l
    |
    |
    O
    -|-
    t e _ t
    Enter a letter: s
    |
    |
    O
    -|-
    t e s t
    YOU WIN!
    C:\jdk1.3.1\bin>java P3
    Pete Dobbins
    Period 5, 7, & 8
    |
    |
    O
    -|-
    Enter a letter: a
    |
    |
    O
    -|-
    Enter a letter: b
    |
    |
    O
    -|-
    Enter a letter: c
    |
    |
    O
    -|
    Enter a letter: d
    |
    |
    O
    |
    Enter a letter: e
    |
    |
    O
    |
    _ e _ _
    Enter a letter: f
    |
    |
    O
    _ e _ _
    Enter a letter: g
    |
    |
    _ e _ _
    YOU LOSE!
    Well i have worked on this and come up with this so far and am having great dificulty as to i am struggling with this class. the beginning is just what i was suppose to comment out. We are suppose to jave for loops for anything that can be put into a for loop also.
    /* Anita Desai
    Period 5
    P4 description:
    1.Declare figure, disp, and soln arrays as attributes of the class
    2.Creation of the arrays will remain inside of main
    3.Delete figure parts
    4.Check for loss (all parts removed)
    5.Implement for loops
    A.Init of appropriate arrays
    B.Test for winner
    C.Test if guess is part of the solution
    D.Removal of correct position from figure
    //bringing the java Input / Output package
    import java.io.*;
    //declaring the program's class name
    class P4
    //declaring arrays as attributes of the class
    public static char figure[];
    public static char disp[];
    public static char soln[];
    // declaring the main method within the class P4
    public static void main(String[] args)
    //print out name and period
    System.out.println("Anita Desai");
    System.out.println("Period 5");
    //creating the arrays
    figure = new char[6];
    soln = new char[4];
    disp = new char[4];
    figure[0] = 'O';
    figure[1] = '-';
    figure[2] = '|';
    figure[3] = '-';
    figure[4] = '<';
    figure[5] = '>';
    soln[0] = 't';
    soln[1] = 'e';
    soln[2] = 's';
    soln[3] = 't';
    //for loop for disp variables
    int i;
    for(i=0;i<4;i++)
    disp='_';
    //Using a while loop to control program flow
    while(true)
    //drawing the board again!
    System.out.println("-----------");
    System.out.println(" |");
    System.out.println(" |");
    System.out.println(" " + figure[0]);
    System.out.println(" " + figure[1] + figure[2] + figure[3]);
    System.out.println(" " + figure[4] + " " + figure[5]);
    System.out.println("\n " + disp[0] + " " + disp[1] + " " + disp[2] + " " + disp[3]);
    //getting input
    System.out.print("Enter a letter: ");
    //declaring a string variable
    String data = " ";
    // call the readString method
    data = readString();
    //retrieves the character at position zero
    char temp;
    temp=data.charAt(0);
    int h;
    for(h=0;h<4;h++)
    if(temp==soln[h])
    disp[h]=soln[h];
    return;
    if(disp[h]==soln[h])
    System.out.println("You Win");
    else
    for(h=0;h<6;h++)
    if(temp!=soln[h])
    figure[h] = ' ';
    return;
    if(disp[h]!=soln[h])
    System.out.println("You Lose");
    ///Test if statements to replace user input with soln if correct
    int j;
    for(j=0;j<4;j++)
    if(temp==soln[j])
    disp[j]=soln[j];
    //declared the readString method, we specified that it would
    //be returning a string
    public static String readString()
    //make connection to the command line
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    //declaring a string variable
    String s = " ";
    //try to do something that might cause an error
    try
    //reading in a line from the user
    s = br.readLine();
    catch(IOException ex)
    //if the error occurs, we will handle it in a special way
    //give back to the place that called us
    //the string we read in
    return s;
    If anyone cann please help me i would greatly appreciate it. I have an exam coming up on wednesday also so i really need to understand this material and see where my mistakes are. If anyoone knows how to delete the parts of the hangman figure one by one each time user guessesincorrectly i would appreciate it greatly. Any other help in solving this program would be great help. thanks.

    Hi thanks for responding. Well to answer some of your questions. The professors instructions are the first 2 paragraphs of my post up until the ende of the output which is You lose!. I have to have the same output as the professor stated which is testing for a winner and loser. Yes the program under the output is what i have written so far. This is the 3rd project and in each we add a little piece to the game. I have no errors when i run the program my problem is when it runs it just prints the hangman figure, disp and then asks user ot enter a letter. Well once i enter a letter it just prints that letter to the screen and the prgram ends.
    As far as the removal of the parts. the solution is TEST. When the user enters a letter lets say Tthen the figure should display again with the disp and filled in solution with T. Then ask for a letter again till user has won and TEST has been guessed correctly. Well then we have to test for a loser. So lets the user enters a R, well then the right leg of the hangman figure should be blank indicating a D the other leg will be blank until the parts are removed and then You lose will be printed to the screen.
    For the program i am suppose to use a FOR LOOPto test for a winner, to remove the parts one at a time, and to see if the parts have been removed if the user guesses incorrectly.
    so as u can see in what i have come up with so far i have done this to test for a winner and loser:
    //declaring a string variable
    String data = " ";
    // call the readString method
    data = readString();
    //retrieves the character at position zero
    char temp;
    temp=data.charAt(0);
    int h;
    for(h=0;h<4;h++)
    if(temp==soln[h])
    disp[h]=soln[h];
    return;
    if(disp[h]==soln[h])
    System.out.println("You Win");
    else
    for(h=0;h<6;h++)
    if(temp!=soln[h])
    figure[h] = ' ';
    return;
    if(disp[h]!=soln[h])
    System.out.println("You Lose");
    Obviously i have not writtern the for loops to do what is been asked to have the proper output. the first for loop i am trying to say if the user input is equal to the soln thencontinue till all 4 disp are guessed correctly and if all the disp=soln then the scrren prints you win.
    then for the incorrect guesses i figured if the user input does not equal the soln then to leave a blank for the right leg and so on so i have a blank space for the figure as stated
    :for(h=0;h<6;h++)
    if(temp!=soln[h])
    figure[h] = ' ';
    well this doesnt work and im not getting the output i wanted and am very confused about what to do. I tried reading my book and have been trying to figure this out all night but i am unable to. I'm going to try for another hr then head to bed lol its 4am. thanks for your help. Sorry about posting in two different message boards. I wont' do it again. thanks again, anita

  • Plz help me on the hangman code

    Consider the venerable "hangman" game, in which a player attempts to guess a word one letter at a time. If you are unfamiliar with hangman, simply google it; you'll be playing in no time.
    Consider the following abstract view of hangman. The input is an unknown word and a sequence of character guesses. There is also an implicit parameter, which is the number of incorrect guesses that may be made before losing the game. Even though you wouldn't implement an interactive hangman game this way, let's model this as:
    static public int hangman (String puzzle, String guesses, int limit)
    Requires: puzzle != null, guesses != null, limit >=0
    Effects: returns the number of the guess that solves the
    puzzle within the given limit on incorrect guesses.
    If the puzzle is not solved within the limit, returns -1.
    e.g.
    hangman ("cat", "abct", 1) is 4 (solved)
    hangman ("cat", "abct", 0) is -1 (hit the limit)
    hangman ("cat", "abcd", 5) is -1 (gave up)
    I wrote the following code but it gives me an error of array index out of bounds exception though it compiles correctly. If someone can help me in correcting the code or point out my mistake.
    public class hangman
    public static int hang(String puz,String gue,int lim)
         int i,j,flag=0,ret=0;
         char p[],g[];
         p=puz.toCharArray();
         g=gue.toCharArray();
         one:
              for(i=0;i<g.length;i++)
                   two:
                   for(j=0;j<p.length;j++)
                        if(g==p[j])
                             //take the element off the p array and resize p
                             if(p.length==1)
                             break one;
                             else
                             char b[]=new char[p.length];
                             for(int k=j+1;k<p.length;k++)
                                  p[k-1]=p[k];
                                  b=p;
                                  p=new char[p.length-1];
                             for(int l=0;i<p.length;l++)
                             p[l]=b[l];
                             continue one;
                        else
                        if(j==p.length-1)
                             flag++;
                        else
                        continue two;
              if(flag>lim)
              return -1;
              else
              return 0;
    public static void main(String args[])
    int ret;
    ret=hang("cat","abct",1);
    System.out.println(ret);

    I wrote the following code but it gives me an error
    of array index out of bounds exception though it
    compiles correctly.I just want to point out a fundamental misunderstanding that this statement suggests you have.
    Compiling just converts your source code into equivalent bytecode. The only errors you'll get during compilation are if the syntax is bad (like you forgot a semicolon, misspelled a method name, have an extra closing brace, etc.) or if you're trying to ues a vairialbe that the copmiler can't be sure will have been initialized, etc.
    Compilation does NOT execute your code, and it has no way to determine the logical problem with, for instance, int[] arr = new int[0];
    int x = arr[999]; The fact that x has zero elements and you're trying to access element 999 only comes to light at execution time.
    So "I get an error at runtime even though it compiles fine" is kind of meaningless.
    Note that I'm not trying to pick on you here. I just want to shift your thinking away from this fundamental misconception you seem to have.

  • Help with Hangman program

    I have been working on this program for more than a week. It is a Hangman program that is supposed to get input from a dialog box when the Guess button is clicked. Then the frame should display the word like so -a--- if the word is "magic." It does not work. If it runs at all it displays some weird output like random letters and numbers. Any help would be greatly appreciated. import java.awt.* ;
    import java.awt.event.*;
    import javax.swing.*;
    import java.lang.String;
    import java.io.*;
    public class HangmanGUI extends JFrame implements ActionListener
    char[] word = {'m','a','g','i','c'};
    String strword = "magic";
    int guesses;
    String guess;
    char chguess;
    JTextField Word = new JTextField(10);
    JButton Guess = new JButton("Guess");
    char[] GuessedSoFar= {'-','-','-','-','-'};
    String ToDisplay;
      public HangmanGUI()  
        setTitle( "-Hangman-" );
    Word.setEditable( false );
        getContentPane().setLayout(new FlowLayout()); 
        getContentPane().add(Word);
        getContentPane().add(Guess);
        Guess.addActionListener( this );
    public void actionPerformed( ActionEvent evt) //throws IOException
      // The application
    // try{
            guess=JOptionPane.showInputDialog ("Enter a guess: ");
         chguess=guess.charAt(0);
    // catch(IOException ex ){
    //       Word.setText("Sorry");
         int e=0;
    for(int i = 0; i<=strword.length(); i++);{
            if(chguess==strword.charAt(e)){
                    GuessedSoFar[e]=chguess;}
              e++;
    ToDisplay="";
    for (int q=0; q<=strword.length();q++){
         ToDisplay+=GuessedSoFar[q] ;
    Word.setText(" "+ToDisplay);
      public static void main ( String[] args ) throws IOException
        HangmanGUI HangmanApp  = new HangmanGUI() ;
        WindowQuitter wquit = new WindowQuitter();
        HangmanApp.addWindowListener( wquit );
        HangmanApp.setSize( 200, 100 );    
        HangmanApp.setVisible( true );        
    class  WindowQuitter  extends WindowAdapter
      public void windowClosing( WindowEvent e )
        System.exit( 0 );  
    }

    well, try to change your code, so that the for things don't go up to the length of the String
    import java.awt.* ;
    import java.awt.event.*;
    import javax.swing.*;
    import java.lang.String;
    import java.io.*;
    public class HangmanGUI extends JFrame implements ActionListener {
      char[] word = {'m','a','g','i','c'};
      String strword = "magic";
      int guesses;
      String guess;
      char chguess;
      JTextField Word = new JTextField(10);
      JButton Guess = new JButton("Guess");
      char[] GuessedSoFar= {'-','-','-','-','-'};
      String ToDisplay;
      public HangmanGUI() {
        setTitle( "-Hangman-" );
        Word.setEditable( false );
        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(Word);
        getContentPane().add(Guess);
        Guess.addActionListener( this );
      public void actionPerformed( ActionEvent evt) {
        guess=JOptionPane.showInputDialog ("Enter a guess: ");
        chguess=guess.charAt(0);
        int e=0;
        for(int i = 0; i<strword.length(); i++) {
          if(chguess==strword.charAt(e)){
            GuessedSoFar[e]=chguess;}
          e++;
        ToDisplay="";
        for (int q=0; q<strword.length();q++){
          ToDisplay+=GuessedSoFar[q] ;
        Word.setText(" "+ToDisplay);
      public static void main ( String[] args ) throws IOException {
        HangmanGUI HangmanApp = new HangmanGUI() ;
        WindowQuitter wquit = new WindowQuitter();
        HangmanApp.addWindowListener( wquit );
        HangmanApp.setSize( 200, 100 );
        HangmanApp.setVisible( true );
    class WindowQuitter extends WindowAdapter {
      public void windowClosing( WindowEvent e ){
        System.exit( 0 );
    }

  • Console Hangman game HELP!!!

    I have to construct a hangman game, and am having some trouble with showing the letters of the word that is guess. Also, I cannot figure out where to put
    public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
    in my code to make it case insensitive. And my other big problem is that I cannot get the game to exit once the player guesses then enitre word correctly. Any suggestions will help.
    import java.util.*;
    import java.io.*;
    public class hangman
         public static void main(String [] args) throws IOException
              //     public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
              int maxTries = 7;
              int wordLength;
              boolean solved;
              StringBuffer guessedLetters = new StringBuffer();
              //the fileScan gets the first word for the game
              Scanner fileScan = new Scanner(new FileInputStream("words.txt"));
              String secretWord = fileScan.next();
              //Creates a StringBuffer for the viewing of the letters guessed
              StringBuffer word = new StringBuffer();
              for(int i = 0; i <= secretWord.length(); i++)
              word.append("_");
              System.out.println("Welcome to the game of HANGMAN!!!!");
              System.out.println("You will have 7 chances to guess what the word is.");
              //     System.out.println("Your word is " + wordLength + " letters long.");
                   String letter;
                   while(maxTries > 0 && (word.equals(secretWord)) == false)
                   System.out.println(word.equals(secretWord));
                   System.out.println("The letters that you have guessed are: " + guessedLetters);
                   System.out.println("The word so far is: " + word);
                   System.out.print("Please enter a letter to guess: ");
                   Scanner inScan = new Scanner(System.in);
                   letter = inScan.next();
                   guessedLetters.append(letter + " ");     
                   if(secretWord.indexOf(letter) != (-1))
                             int addedLetter = secretWord.indexOf(letter);
                             word.replace(addedLetter, addedLetter, letter);
                              word.setLength(secretWord.length());
                   else
                        maxTries--;
                   System.out.println("You have " + maxTries + " wrong guesses left.");
    }THANKS

    I have to construct a hangman game, and am having some trouble with showing the letters of the word that is guess. Also, I cannot figure out where to put
    public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
    in my code to make it case insensitive. And my other big problem is that I cannot get the game to exit once the player guesses then enitre word correctly. Any suggestions will help.
    import java.util.*;
    import java.io.*;
    public class hangman
         public static void main(String [] args) throws IOException
              //     public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
              int maxTries = 7;
              int wordLength;
              boolean solved;
              StringBuffer guessedLetters = new StringBuffer();
              //the fileScan gets the first word for the game
              Scanner fileScan = new Scanner(new FileInputStream("words.txt"));
              String secretWord = fileScan.next();
              //Creates a StringBuffer for the viewing of the letters guessed
              StringBuffer word = new StringBuffer();
              for(int i = 0; i <= secretWord.length(); i++)
              word.append("_");
              System.out.println("Welcome to the game of HANGMAN!!!!");
              System.out.println("You will have 7 chances to guess what the word is.");
              //     System.out.println("Your word is " + wordLength + " letters long.");
                   String letter;
                   while(maxTries > 0 && (word.equals(secretWord)) == false)
                   System.out.println(word.equals(secretWord));
                   System.out.println("The letters that you have guessed are: " + guessedLetters);
                   System.out.println("The word so far is: " + word);
                   System.out.print("Please enter a letter to guess: ");
                   Scanner inScan = new Scanner(System.in);
                   letter = inScan.next();
                   guessedLetters.append(letter + " ");     
                   if(secretWord.indexOf(letter) != (-1))
                             int addedLetter = secretWord.indexOf(letter);
                             word.replace(addedLetter, addedLetter, letter);
                              word.setLength(secretWord.length());
                   else
                        maxTries--;
                   System.out.println("You have " + maxTries + " wrong guesses left.");
    }THANKS

  • Runtime Error in Hangman App

    Good evening all,
    I have written the following code for a CS assignment. All seems well except for a few issues with the alignment of the ASCII art but I am still tweaking it a bit. The major problem is if the user presses the enter button instead of using the mouse several body parts are shown regardless if the letter entered is part of the hidden word or not. It doesn't do it with each word but only every other one. I'd appreciate being pointed in the right direction so I can get it to run either way (enter and/or mouse). Thanks in advance.
    import java.util.*;
    import javax.swing.*;
    public class Hangman
      public static void main (String [] args)
        //declaration of variables
        boolean playing = true;      // true while playing game
        boolean correct = false;     // false when ending game  
        int i;                       // temp variable for index loop
        int length;                  // length of secret word
        int guessRemaining;          // wrong guesses remaining
          String c = "";               // temp variable for character
        String word;                 // secret word
        String hiddenLetters = "";   // use to hide letters of word
          String wrongLetters = "";    // letters not in secret word
        String temp = "";            // temp variable for Strings     
        guessRemaining = 6;          // start w/ no wrong guesses
        word = JOptionPane.showInputDialog(null, "Enter the secret word.");   
        length = word.length();      // Player 1 enters a word.
        for (i=0; i < length; i++)
          hiddenLetters = hiddenLetters + "-";  // Letters of hidden word replaced with -
        while (playing == true){     // Player 2 begins game
               correct = false;
          if (guessRemaining==6){       
            c = JOptionPane.showInputDialog(null,"\t---------- \n\t |    |   \n\t |      \n\t |  \n\t | \n\t   | \n\t=======\n"+
                                                wrongLetters + "\n"+ hiddenLetters);
          if (guessRemaining==5)
            c = JOptionPane.showInputDialog(null,"\t---------- \n\t |    | \n\t |     () \n\t |  \n\t | \n\t   | \n\t=======\n"+
                                                wrongLetters + "\n"+ hiddenLetters);
          if (guessRemaining==4)
            c = JOptionPane.showInputDialog(null,"\t---------- \n\t |    | \n\t |   () \n\t |       | \n\t   | \n\t | \n\t=======\n"+
                                                wrongLetters + "\n"+ hiddenLetters);
          if (guessRemaining==3)
            c = JOptionPane.showInputDialog(null,"\t---------- \n\t |    | \n\t |   () \n\t |       |--\n\t  | \n\t | \n\t=======\n"+
                                                wrongLetters + "\n"+ hiddenLetters);
          if (guessRemaining==2)
            c = JOptionPane.showInputDialog(null,"\t---------- \n\t |    | \n\t |   () \n\t |     --|-- \n\t | \n\t | \n\t | \n\t=======\n"+
                                                wrongLetters + "\n"+ hiddenLetters);
          if (guessRemaining==1)
            c = JOptionPane.showInputDialog(null,"\t---------- \n\t |    | \n\t |   () \n\t |     --|-- \n\t | \n\t | \n\t | \n\t=======\n"+ 
                                                wrongLetters + "\n"+ hiddenLetters);
          if (guessRemaining==0){
              JOptionPane.showMessageDialog(null,"\t---------- \n\t |    | \n\t |   () \n\t |     --|-- \n\t |      | \n\t | \n=======\n\n+YOU'VE BEEN\n    HANGED!!!\n"+ wrongLetters + "\n"+ hiddenLetters);
              playing = false;
          for (i = 0; i < length; i++)       
            if (hiddenLetters.charAt(i)!= '-'){             // '-' replaced w/ correct letter
              temp = temp + hiddenLetters.charAt(i);}
            else if (word.charAt(i)==c.charAt(0)){
              temp = temp + c.charAt(0);
              correct = true;
            else {
             temp = temp + "-";
          hiddenLetters = temp;
          temp = "";
          if (correct == false){
            wrongLetters = wrongLetters + c;
            guessRemaining = guessRemaining - 1;
          if (hiddenLetters.equals(word)){
            JOptionPane.showMessageDialog(null, "Awesome Job! You Won The Game!");
            playing = false;
    }// End program

    Flounder,
    I guess I should have been more explicit in my question. I certainly wasn't looking for someone to fix the code for me or spoonfeed me the answer. I was only wanting to be pointed in the right direction about how to deal with this. I haven't encountered this type of error before and after testing it over 50 times and trying everything I've learned in the past few months and doing a search on here and reviewing the tutorials I was still stuck. Sorry about that. Thanks for the info and the advice regarding the other line of code. I really do appreciate the help.

  • Hangman

    I need help, my hangman works, but I want the hangman to show a GUI shape for each wrong answer. help me out! thanks
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.io.*;
    import javax.swing.*;
    public class Hangman extends Applet implements KeyListener, Runnable, MouseListener
         final int maxNumTries = 5;
         final int wordGuessed = 20;
         final int Image1 = 0;
         final int Image2 = 1;
         final int gameboardWidth = 40;//default size of the game board
         final int gameboardHeight = 60;
         int danceSequenceNum = -1;
         int danceDirection = 1;
         char secretWord[];
         int secretWordGuessed;
         char wrongLetters[];
         int wrongLettersCount;
         char word[];
         int wordLen;
         Font wordFont;
         FontMetrics wordFontMetrics;
         MediaTracker mediaTracker;
         Image hangImages[];
         Thread hangmanThread;
         Image hangmanImages[];
         int danceHeight = 68;
         int hangmanImagesLen = 0;
    public void init ()
    int i;
    mediaTracker = new MediaTracker ( this );
    hangmanImages = new Image [40];
    for ( i = 0; i < 7; i ++)
    Image im = getImage( getDocumentBase(), " images/dancing-duke.gif" + i);
    mediaTracker . addImage( im , Image1 );
    hangmanImages [ hangmanImagesLen ++] = im ;
    hangImages = new Image [ maxNumTries ];
    for ( i = 0; i < maxNumTries ; i ++)
    Image im = getImage( getDocumentBase(), " images/hanging-duke" + ( i + 1) + " .gif");
    mediaTracker . addImage( im , Image2 );
    hangImages [ i ] = im ;
    wrongLettersCount = 0;
    wrongLetters = new char [ maxNumTries ];
    secretWordGuessed = 0;
    secretWord = new char [ wordGuessed ];
    word = new char [ wordGuessed ];
    wordFont = new java.awt.Font ("Serif", Font . BOLD, 22);
    wordFontMetrics = getFontMetrics(wordFont);
    addMouseListener( this );
    addKeyListener( this );
    String wordlist[] = {" abstraction", " ambiguous", " arithmetic", " backslash", " bitmap",
    " circumstance", " combination", " consequently", " consortium", " decrementing",
    " dependency", " disambiguate", " dynamic", " encapsulation", " equivalent",
    " expression", " facilitate", " fragment", " hexadecimal", " implementation",
    " indistinguishable", " inheritance", " internet", " java", " localization",
    " microprocessor", " navigation", " optimization", " parameter", " patrick"};
    public void paint (Graphics g)//creates the hangman gameboard
    int imageW = gameboardWidth ;
    int imageH = gameboardHeight ;
    int baseWidth = 30;
    int baseHeight = 15;
    Font font;
    FontMetrics fontMetrics;
    int i, x, y;
    g . drawLine(baseWidth / 2, 5, baseWidth / 2, 2 * imageH - baseHeight / 2);
    g . drawLine(baseWidth / 2, 5, baseWidth + imageW / 2, 0);
    g . drawLine(baseWidth + imageW / 2, 0, baseWidth + imageW / 2, imageH / 6);
    g . fillRect(2, 2 * imageH - baseHeight , baseWidth , baseHeight );
    font = new java.awt.Font (" SansSerif", Font . BOLD, 14);
    fontMetrics = getFontMetrics(font);
    x = imageW + baseWidth ;
    y = fontMetrics . getHeight();
    g . setFont( font );
    g . setColor( Color . black);
    for ( i = 0; i < wrongLettersCount ; i ++)
    g . drawChars( wrongLetters , i , 1, x , y );
    x += fontMetrics . charWidth( wrongLetters [ i ]) + fontMetrics . charWidth(' ');
    if ( secretWordGuessed > 0)
    int Mwidth = wordFontMetrics . charWidth('O');
    int Mheight = wordFontMetrics . getHeight();
    g . setFont( wordFont );
    g . setColor( Color . red);
    x = 0;
    y = getSize(). height - 1;
    for ( i = 0; i < secretWordGuessed ; i ++)
    g . drawLine( x , y , x + Mwidth , y );
    x += Mwidth + 3;
    x = 0;
    y = getSize(). height - 3;
    g . setColor( Color . blue);
    for ( i = 0; i < secretWordGuessed ; i ++)
    if ( word [ i ] != 0)
          g . drawChars( word , i , 1, x , y );
    x += Mwidth + 3;
    if ( wordLen < secretWordGuessed && wrongLettersCount > 0)
    //g . drawImage( hangImages [ wrongLettersCount - 1], baseWidth , imageH / 3, this );
    public void update ( Graphics g)
    if ( wordLen == 0)
    //g . clearRect(0, 0, getSize(). width, getSize(). height);
    paint( g );
    else if ( wordLen == secretWordGuessed )
    if(danceSequenceNum < 0)
    g . clearRect(0, 0, getSize(). width, getSize(). height);
    paint( g );
    danceSequenceNum = 0;
    //updateGame( g );
    else
    paint( g );
    public void newGame ()
    int i;
    hangmanThread = null ;
    String s = wordlist [ ( int ) Math . floor( Math . random() * wordlist . length)];
    secretWordGuessed = Math . min( s . length(), wordGuessed );
    for ( i = 0; i < secretWordGuessed ; i ++)
    secretWord [ i ] = s . charAt( i );
    for ( i = 0; i < wordGuessed ; i ++)
    word [ i ] = 0;
    wordLen = 0;
    for ( i = 0; i < maxNumTries ; i ++)
    wrongLetters [ i ] = 0;
    wrongLettersCount = 0;
    repaint();
    public void start ()
    requestFocus();
    try
    mediaTracker . waitForID( Image2 );
    catch ( InterruptedException e){} mediaTracker . checkAll( true );
    if ( secretWordGuessed == wordLen || wrongLettersCount == maxNumTries )
    newGame();
    public void stop ()
    //hangmanThread = null ;
    public void run ()
    public void keyPressed ( KeyEvent e)
    public void keyReleased ( KeyEvent e)
    int i;
    boolean found = false ;
    char key = e . getKeyChar();
    if ( secretWordGuessed == wordLen || wrongLettersCount == maxNumTries )
    newGame();
    e . consume();
    return ;
    /*if ( key < 'a' || key > 'z')
    e . consume();
    return ;
    for ( i = 0; i < secretWordGuessed ; i ++)
    if ( key == word [ i ])
    found = true ;
    e . consume();
    return ;
    if (! found )
    for ( i = 0; i < maxNumTries ; i ++)
    if ( key == wrongLetters [ i ])
    found = true ;
    e . consume();
    return ;
    if (! found )
    for ( i = 0; i < secretWordGuessed ; i ++)
    if ( key == secretWord [ i ])
    word [ i ] = ( char ) key ;
    wordLen ++;
    found = true ;
    if ( found ) if ( wordLen == secretWordGuessed )
    if (! found ) if ( wrongLettersCount < wrongLetters . length)
    wrongLetters [ wrongLettersCount ++] = ( char ) key ;
    if ( wrongLettersCount < maxNumTries )
    else
    for ( i = 0; i < secretWordGuessed ; i ++)
          word [ i ] = secretWord [ i ];
    if ( wordLen == secretWordGuessed )
    //danceSequenceNum = -1;
    repaint();
    e . consume();
    public void keyTyped ( KeyEvent e)
    public void mouseClicked ( MouseEvent e)
    public void mouseReleased ( MouseEvent e)
    public void mousePressed ( MouseEvent e)
    int i;
    requestFocus();
    if ( secretWordGuessed > 0 && ( secretWordGuessed == wordLen || wrongLettersCount == maxNumTries ))
    newGame();
    else
    e . consume();
    public void mouseEntered ( MouseEvent e)
    public void mouseExited ( MouseEvent e)
    }

    Look at what you posted and ask yourself whether anyone might be able to read that, a huge pile of statements, unformatted, no comments... and your problem description is not very clear either.

  • Issues with hangman activity in captivate 7

    Hi,
    I am using the hangman activity in some of my projects. There are two issues being faced:
    When I test the published file in scormcloud, it works fine. The screen automatically progresses to the next slide once the learner completes the activity (I am using IE or firefox browser). However, when my client tests it, they get stuck after this activity, because the slide doesn't progress (they're testing on Chrome browser). Is this a browser issue?
    Secondly, for the learner to move from one question to another after completing it, the button label reads 'Retry', which is not correct because you want them to continue and not retry a word. Is there a way to customize the button labels for these new interactions?
    Your advise would be highly appreciated!
    Divya

    Divya, I have had similar problems with the puzzle widget. In the end we cannot make learner tools that only work on certain browsers. Users use different browsers. And that is that.
    Adobe did not round off these widget tools properly. I actually wonder how they passed any form of QA.
    I have not specifically used the hangman widget yet, However, when a learner does not complete the puzzle widget in time, it just hangs (freezes) right there! So I added a "continue" button that actually runs the slide again (so widget runs again) and allows the learner to try again. In the same way you could just add a continue button when and where your require it. You might have to use some advanced action to co-ordinate the lot.
    If you have not worked with advanced actions before, now is the time to learn. Drink a Red Bull (It is not really bad for you) and watch the series of videos that explain advanced actions on YouTube. You will need the Red Bull to maintain focus . Just make enough time available and be patient. You will get it right.  It will help you overcome many of the Captivate problems.

  • Need algorithm help

    I need some help with my 3 class hangman program.
    whenever the program is run, it doesn't function as intended when a letter is entered. Any advice is greatly appreciated.
    Here's what I have so far:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    //<applet code="Hangman.class" width=400 height=400>
    //</applet>
    public class Hangman extends JApplet implements ActionListener
         private final int WIDTH = 400;
         private final int HEIGHT = 400;
         private JPanel panel,tools;
         private JLabel inputLabel;
         private Hang drawing;
         private JTextField guess;
         RandomWord t = new RandomWord();
         public String answer = t.getWord();
         public void init()
              tools = new JPanel();
              tools.setLayout(new BoxLayout(tools,BoxLayout.X_AXIS));
              tools.setBackground(Color.yellow);
              tools.setOpaque(true);
              guess = new JTextField(1);
              guess.addActionListener(this);
              inputLabel = new JLabel("Enter Guess:");
              tools.add(inputLabel);
              tools.add(guess);
              drawing = new Hang();
              panel = new JPanel();
              panel.add(tools);
              panel.add(drawing);
              getContentPane().add(panel);
              setSize(WIDTH,HEIGHT);
         public void actionPerformed(ActionEvent event)
              String g = guess.getText();
              int incorr = 0;
              int c = 0;
              int i;
              for(i = 0;i<answer.length();i++)
                   if((answer.substring(i,i+1)).equals(g))
                        c++;
                        drawing.setLetter(i,g);
              if(c == 0)
                   incorr++;
                   drawing.setIndex(incorr);
              repaint();
    // class number 2:
    import java.awt.*;
    import javax.swing.JPanel;
    public class Hang extends JPanel
         private final int PAN_HEI = 400;
         private final int PAN_WID = 400;
         private int index;
         private int posNum,corr = 0;
         private String print;
         public Hang()
              setBackground(Color.black);
              setPreferredSize(new Dimension(PAN_WID,PAN_HEI));
         public void setIndex(int v)
              index = v;
         public void setLetter(int y,String s)
              print = s;
              posNum = y + 1;
         public void drawBase(Graphics page)
              setBackground(Color.white);
              page.setColor(Color.black);
              page.fillRect(0,350,150,50);// base
              page.fillRect(0,150,25,200);
              page.fillRect(0,125,100,25);
              page.setColor(Color.gray);
              page.fillRect(84,125,7,50);// rope
              page.setColor(Color.black);
              page.drawOval(75,175,24,25);// head
              page.drawLine(250,55,255,55);
              page.drawLine(260,55,265,55);
              page.drawLine(270,55,275,55);
              page.drawLine(280,55,285,55);     
              page.drawLine(290,55,295,55);
              page.drawLine(300,55,305,55);
              page.drawLine(310,55,315,55);
         public void paintComponent(Graphics page)
              super.paintComponent(page);
              this.drawBase(page);
              if(index == 1)
                   page.drawLine(84,200,84,250);
              if(index == 2)
                   page.drawLine(84,215,34,175);
              if(index == 3)
                   page.drawLine(84,215,116,175);
              if(index == 4)
                   page.drawLine(84,250,50,300);
              if(index == 5)
                   page.drawLine(84,250,100,300);
                   page.drawString("You Lose",250,75);
              if(posNum == 1)
                   corr++;
                   page.drawString(print,250,50);
              if(posNum == 2)
                   corr++;
                   page.drawString(print,260,50);
              if(posNum == 3)
                   corr++;
                   page.drawString(print,270,50);
              if(posNum == 4)
                   corr++;
                   page.drawString(print,280,50);
              if(posNum == 5)
                   corr++;
                   page.drawString(print,290,50);
              if(posNum == 6)
                   corr++;
                   page.drawString(print,300,50);
              if(posNum == 7)
                   corr++;
                   page.drawString(print,310,50);
              if(corr == 7)
                   page.drawString("You Win",250,75);
    //last class :
    import java.util.Random;
    public class RandomWord
         Random g = new Random();
         String w1;
         String w2;
         String w3;
         String w4;
         String w5;
         String w6;
         String w7;
         String w8;
         public RandomWord()
              w1 = "freedom";
              w2 = "justice";
              w3 = "impulse";
              w4 = "destiny";
              w5 = "celsius";
              w6 = "ignited";
              w7 = "believe";
              w8 = "realize";
         public String getWord()
              String x = " ";
              int a = g.nextInt(6);
              if(a == 0) x = w1;
              if(a == 1) x =  w2;
              if(a == 2) x =  w3;
              if(a == 3) x = w4;
              if(a == 4) x = w5;
              if(a == 5) x = w6;
              if(a == 6) x = w7;
              if(a == 7) x = w8;
              return x;
    }I'm a very inexperiencd programmer as you can see.

    Darn, I thought you actually needed algorithm help. But instead all I see is:
    "Here's all my code. It doesn't work right. Let me plop it onto your virtual desk and ask that you just fix it for me. I'm going shopping (or whatever) and will be back soon."

  • My Coding is missing something, can you help please?

    i have three points in the following code which i can't work it out
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.* ;
    public class Hangman extends Applet implements ActionListener, ItemListener
    /* problems
    * 1) should replace all occurences of letter not just 1
    * 2) no of guesses should not be allowed to be <0
    * 3) win/lose message should be in color
    // CONSTANTS
    private static final int EASY = 0;
    private static final int MEDIUM = 1;
    private static final int HARD = 2;
    private static final int BEGINER = 9;
    private static final int INTERMEDIATE = 8;
    private static final int ADVANCED = 7;
    private static final int ANSWER = 26;
    private static final int RESET = 27;
    private static final int STRING_NOT_FOUND = -1;
    private String[][] WorkingArray = new String[][]{
    new String[]{"CAT","WREN","MOUSE","GERBIL"},
    new String[]{"ROSE","GRASS","WILLOW","RAGWORT"},
    new String[]{"SHIRT","JACKET","SANDALS","TROUSERS"}
    private Button[] Keys = new Button[28];
    private CheckboxGroup Diff = new CheckboxGroup();
    private Checkbox[] Levels = new Checkbox[]{
    new Checkbox("Beginner",true,Diff),
    new Checkbox("Intermediate",false,Diff),
    new Checkbox("Advanced",false,Diff)
    private Panel Keypad = new Panel(new GridLayout(4,7));
    private Panel P = new Panel(new FlowLayout());
    private Label Title = new Label("Guess The Word");
    private Label Prompt= new Label ("Guesses Remaining");
    private TextField Word =new TextField(24);
    private TextField Message = new TextField(24);
    private TextField Guesses = new TextField(3);
    private String LongWord = " ";// Long Word
    private String ChaGuess = " ";// Guessed Charactor
    private String s = " " ;
    private int[] Level_Values = new int[]{9,8,7,} ;
    private int Pos = 0 ;
    private int LPos = 0 ;
    private int NoOfGuesses = 9;
    private int NoOfChars = 0 ;
    private int WordLen = 0 ; // length of current word
    private int ArrayIndex = 0;// Array, currently in use
    private int ElementIndex = 0;// element, currently in use
    public void init() { // build gui and register components for events
    this.add(Title);
    this.add(Word);
    this.add(P);
    this.add(Keypad);
    this.add(Message);
    // add radio buttons to gui and register for events
    for (int x = 0 ; x < Levels.length ; x++){
    Levels[x].addItemListener(this);
    this.add(Levels[x]);
    public void start (){
    validate();
    public void stop(){
    invalidate();
    public void destroy(){
    public void actionPerformed( ActionEvent Click){
    int LastPos = 0 ;
    try {    // handle button events
    if (Click.getSource() == Keys[RESET]){
    // Hide Messages and clear TextFields
    Message.setVisible(false);
    Word.setText("");
    LongWord = " " ;
    // Enable Letters
    for (int x = 0 ; x < RESET ; x++){
    Keys[x].setEnabled(true);
    }// for
    // Get Word to Display
    ElementIndex = (int)(Math.random()*4); // random no between 0 - 3
    WordLen = WorkingArray[ArrayIndex][ElementIndex].length();
    NoOfChars = WordLen ;
    for (int x = 0 ; x < WordLen; x++){
    LongWord = LongWord +"-" ;
    } // for
    Word.setText(LongWord);
    NoOfGuesses = Level_Values[ArrayIndex] ;
    Guesses.setText(LongWord.valueOf(NoOfGuesses));
    } // if
    else if (Click.getSource() == Keys[ANSWER]){
    Word.setText(WorkingArray[ArrayIndex][ElementIndex]);
    Guesses.setText(" ");
    // Disable Letters
    for (int x = 0 ; x < RESET; x++){
    Keys[x].setEnabled(false);
    }// for
    }// else if
    else{
    //event came from a letter
    // get object from awt.event, cast to button to use label
    ChaGuess=( ((Button)Click.getSource()).getLabel() );
    LPos = WorkingArray[ArrayIndex][ElementIndex].indexOf(ChaGuess) ;
    Pos = WorkingArray[ArrayIndex][ElementIndex].lastIndexOf(ChaGuess);
    if (Pos == STRING_NOT_FOUND){
    --NoOfGuesses ;
    Guesses.setText(LongWord.valueOf(NoOfGuesses));
    if (NoOfGuesses == 0 ) {
    Message.setVisible(true);
    Message.setText("You Lose");
    } //if
    else {
    if (LPos == Pos){
    LongWord = (LongWord.substring(0,Pos )
    + ChaGuess + LongWord.substring(Pos+1,WordLen));
    --NoOfChars;
    LastPos = Pos ;
    else {
    LongWord = (LongWord.substring(0,Pos )
    + ChaGuess + LongWord.substring(Pos+1,WordLen));
    --NoOfChars;
    Pos = WorkingArray[ArrayIndex][ElementIndex].indexOf(ChaGuess,LPos+1) ;
    if ( Pos != STRING_NOT_FOUND) {
    LongWord = (LongWord.substring(0,Pos )
    + ChaGuess + LongWord.substring(Pos+1,WordLen));
    --NoOfChars;
    Word.setText(LongWord);
    if (NoOfChars == 0 ) {
    Message.setVisible(true);
    Message.setText("You Win");
    }// end of try block
    catch ( Exception E ){ // catches all  exceptions
    finally {
    invalidate(); // mark window as needing to be redrawn
    validate(); // redraw window
    } // actionPerformed
    public void itemStateChanged(ItemEvent Check){
    // handle checkbox events
    if (Diff.getSelectedCheckbox() == Levels[EASY]){
    ArrayIndex = EASY ;
    else if (Diff.getSelectedCheckbox() == Levels[MEDIUM]){
    ArrayIndex = MEDIUM ;
    else if (Diff.getSelectedCheckbox() == Levels[HARD]){
    ArrayIndex = HARD ;
    Guesses.setText(s.valueOf(Level_Values[ArrayIndex]));
    invalidate();
    validate();
    public Hangman() {
    char Tit = 'A';
    String ButtonTitle = "A" ;
    // construct keyboard and register for ActionEvents
    for (int Cnt = 0;Cnt< Keys.length ; Tit++, Cnt++){
    ButtonTitle = ButtonTitle.valueOf(Tit);
    Keys[Cnt] = new Button(ButtonTitle);
    Keys[Cnt].setEnabled(false);
    Keys[Cnt].addActionListener(this);
    Keypad.add(Keys[Cnt]);
    Guesses.setText(ButtonTitle.valueOf(NoOfGuesses));
    Guesses.setEditable(false); // make TextField ReadOnly
    Word.setEditable(false); // make TextField ReadOnly
    Message.setVisible(false);
    P.add(Prompt);
    P.add(Guesses);
    Keys[ANSWER].setLabel("Answer");
    Keys[RESET].setLabel("Reset");
    Keys[RESET].setEnabled(true);
    }// Hangman1
    you help is appreciated

    Change
    if (NoOfGuesses == 0 ) {
    Message.setVisible(true);
    Message.setText("You Lose");
    } //if
    to,
    if (NoOfGuesses == 0 ) {
    Message.setVisible(true);
    Message.setForeground(Color.red);
    Message.setText("You Lose");
    for (int x = 0 ; x < RESET ; x++){
    Keys[x].setEnabled(false);
    }// for
    } //if
    set
    Message.setForeground(Color.red);
    for the You Win also

  • Help with AudioClip files

    Hi, i got a problem with using AudioClip classes with jars, my application works normally when i use it with the command prompt, but it doesn't with a jar file, i specified the classpath in the manifest file and the main class as well, but this line of code throws me a NullPointerException:
    song = Applet.newAudioClip(getClass().getResource("./50_cent_-_candy_shop.mid"));The weird thing is that the images work, but not the file.
    Help is appreciated.

    Wow, when i use it in the command line it gives me the right path, but when i use it on the jar file it returns null.
    C:\Java\Programas\Hangman>java Play
    file:/C:/Java/Programas/Hangman/
    C:\Java\Programas\Hangman>jar -cfm Hangman.jar Manifest.mf *.class images *.mid
    C:\Java\Programas\Hangman>java -jar Hangman.jar
    Exception in thread "main" java.lang.NullPointerException
    at HangmanGUI.setEvents(HangmanGUI.java:223)
    at HangmanGUI.setComponents(HangmanGUI.java:144)
    at HangmanGUI.<init>(HangmanGUI.java:98)
    at Play.main(Play.java:5)

  • Assignment Due TODAY - NEED HELP

    My program is below and I have already setup a Client Server Connection for a hangman game, but I need help sending and displaying the options selected by the user. PLEASE HELP
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ClientApp extends JFrame
        // Declarations used in program
        private Socket server;
        ObjectOutputStream out;
        ObjectInputStream in;
        int length = 0; // Length of word received by Server
        String guess;
        String lines;
        String secret;
        int chances = 0; // Count to Hold no of chances by user
        int categorySelected ;
        // GUI Declarations
        private JButton btnMovies;
        private JButton btnSport;
        private JButton btnExit, btnNew;
        private JButton a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z;
        private JLabel lblWelcome, lblCategory , lblChances;
        private JPanel pan1, pan2, pan3, pan4, pan5, pan6, pan7, pan8, pan9, pan10;
        private JTextArea answer;
        private JTextField txtCategory, txtChances;
       // CONSTRUCTOR
        public ClientApp()
            setLayout(new FlowLayout());
            pan1 = new JPanel();
            pan3 = new JPanel();
            pan2 = new JPanel();
            lblWelcome = new JLabel("Welcome to Hangman.\n\n Please select a category.");
            pan1.add(lblWelcome);
            btnMovies = new JButton("Movie Titles");
            pan3.add(btnMovies);
            btnSport = new JButton("Sport");
            pan3.add(btnSport);
            btnNew = new JButton("New Game");
            pan3.add(btnNew);
            btnExit = new JButton("Exit");
            pan2.add(btnExit);
            pan9 = new JPanel();
            txtCategory = new JTextField(10);
            pan9.add(txtCategory);
            pan8 = new JPanel();
            answer = new JTextArea(3,30);
            answer.setEditable(false);
            pan8.add(answer);
            add(pan1);
            add(pan3);
            add(pan2);
            add(pan9);
            add(pan8);
            btnExit.addActionListener(
                new ActionListener()
                    public void actionPerformed(ActionEvent event)
                        System.exit(0);
            btnMovies.addActionListener(
                new ActionListener()
                    public void actionPerformed(ActionEvent event)
                       enableButtons();
                       btnSport.setEnabled(false);
                       btnNew.setEnabled(true);
                       txtCategory.setText("Movies");
                       categorySelected = 0;
                       processClient();
            btnSport.addActionListener(
                new ActionListener()
                    public void actionPerformed(ActionEvent event)
                       enableButtons();
                       btnMovies.setEnabled(false);
                       btnSport.setEnabled(false);
                       btnNew.setEnabled(true);
                       txtCategory.setText("Actors Names");
                       categorySelected = 1;
                       processClient();
            btnNew.addActionListener(
                new ActionListener()
                    public void actionPerformed(ActionEvent event)
                        enableButtons();
                        btnSport.setEnabled(true);
                        btnMovies.setEnabled(true);
                        btnNew.setEnabled(false);
                        chances = 0;
                        communicate();
            buttons();
            disableButtons();
            btnNew.setEnabled(false);
            // Attempt to establish connection to server
            try
                // Create socket
                server = new Socket("localhost", 8008);
            catch (IOException ioe)
                System.out.println("IOException: " + ioe.getMessage());
        // Method to add Alphabetic Buttons to GUI
        public void buttons()
                pan4 = new JPanel();
                pan5 = new JPanel();
                pan6 = new JPanel();
                pan7 = new JPanel();
             a = new JButton("A");
             b = new JButton("B");
             c = new JButton("C");
             d = new JButton("D");
             e = new JButton("E");
             f = new JButton("F");
             g = new JButton("G");
             h = new JButton("H");
             i = new JButton("I");
             j = new JButton("J");
             k = new JButton("K");
             l = new JButton("L");
             m = new JButton("M");
             n = new JButton("N");
             o = new JButton("O");
             p = new JButton("P");
             q = new JButton("Q");
             r = new JButton("R");
             s = new JButton("S");
             t = new JButton("T");
             u = new JButton("U");
             v = new JButton("V");
             w = new JButton("W");
             x = new JButton("X");
             y = new JButton("Y");
             z = new JButton("Z");
            pan4.add(a);
            pan4.add(b);
            pan4.add(c);
            pan4.add(d);
            pan4.add(e);
            pan4.add(f);
            pan5.add(g);
            pan5.add(h);
            pan5.add(i);
            pan5.add(j);
            pan5.add(k);
            pan5.add(l);
            pan6.add(m);
            pan6.add(n);
            pan6.add(o);
            pan6.add(p);
            pan6.add(q);
            pan6.add(r);
            pan7.add(s);
            pan7.add(t);
            pan7.add(u);
            pan7.add(v);
            pan7.add(w);
            pan7.add(x);
            pan7.add(y);
            pan7.add(z);
            add(pan4);
            add(pan5);
            add(pan6);
            add(pan7);
            // Button Handler for Alphabet
            ButtonHandler handler = new ButtonHandler();
           a.addActionListener(handler);
           b.addActionListener(handler);
           c.addActionListener(handler);
           d.addActionListener(handler);
           e.addActionListener(handler);
           f.addActionListener(handler);
           g.addActionListener(handler);
           h.addActionListener(handler);
           i.addActionListener(handler);
           j.addActionListener(handler);
           k.addActionListener(handler);
           l.addActionListener(handler);
           m.addActionListener(handler);
           n.addActionListener(handler);
           o.addActionListener(handler);
           p.addActionListener(handler);
           q.addActionListener(handler);
           r.addActionListener(handler);
           s.addActionListener(handler);
           t.addActionListener(handler);
           u.addActionListener(handler);
           v.addActionListener(handler);
           w.addActionListener(handler);
           x.addActionListener(handler);
           y.addActionListener(handler);
           z.addActionListener(handler);
       private class ButtonHandler implements ActionListener
        public void actionPerformed(ActionEvent ae)
                 if (ae.getSource()==a)
                            guess = "a";
                            a.setEnabled(false);
                            sendGuess();
                 if (ae.getSource()==b)
                           guess = "b";
                           b.setEnabled(false);
                           sendGuess();
                 if (ae.getSource()==c)
                             guess = "c";
                             c.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==d)
                             guess = "d";
                             d.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==e)
                             guess = "e";
                             e.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==f)
                             guess = "f";
                             f.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==g)
                             guess = "g";
                             g.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==h)
                             guess = "h";
                             h.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==i)
                             guess = "i";
                             i.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==j)
                             guess = "j";
                             j.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==k)
                             guess = "k";
                             k.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==l)
                             guess = "l";
                             l.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==m)
                             guess = "m";
                             m.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==n)
                             guess = "n";
                             n.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==o)
                             guess = "o";
                             o.setEnabled(false);
                             sendGuess();
                  if (ae.getSource()==p)
                             guess = "p";
                             p.setEnabled(false);
                             sendGuess();
                  if (ae.getSource()==q)
                             guess = "q";
                             q.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==r)
                             guess = "r";
                             r.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==s)
                             guess = "s";
                             s.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==t)
                             guess = "t";
                             t.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==u)
                             guess = "u";
                             u.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==v)
                             guess = "v";
                             v.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==w)
                             guess = "w";
                             w.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==x)
                             guess = "x";
                             x.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==y)
                             guess = "y";
                             y.setEnabled(false);
                             sendGuess();
                 if (ae.getSource()==z)
                             guess = "z";
                             z.setEnabled(false);
                             sendGuess();
            // Method to Disable the buttons          
            public void disableButtons()
                a.setEnabled(false);
                b.setEnabled(false);
                c.setEnabled(false);
                d.setEnabled(false);
                e.setEnabled(false);
                f.setEnabled(false);
                g.setEnabled(false);
                h.setEnabled(false);
                i.setEnabled(false);
                j.setEnabled(false);
                k.setEnabled(false);
                l.setEnabled(false);
                m.setEnabled(false);
                n.setEnabled(false);
                o.setEnabled(false);
                p.setEnabled(false);
                q.setEnabled(false);
                r.setEnabled(false);
                s.setEnabled(false);
                t.setEnabled(false);
                u.setEnabled(false);
                v.setEnabled(false);
                w.setEnabled(false);
                x.setEnabled(false);
                y.setEnabled(false);
                z.setEnabled(false);
            // Method to enable Buttons so user can Click on them
            public void enableButtons()
                a.setEnabled(true);
                b.setEnabled(true);
                c.setEnabled(true);
                d.setEnabled(true);
                e.setEnabled(true);
                f.setEnabled(true);
                g.setEnabled(true);
                h.setEnabled(true);
                i.setEnabled(true);
                j.setEnabled(true);
                k.setEnabled(true);
                l.setEnabled(true);
                m.setEnabled(true);
                n.setEnabled(true);
                o.setEnabled(true);
                p.setEnabled(true);
                q.setEnabled(true);
                r.setEnabled(true);
                s.setEnabled(true);
                t.setEnabled(true);
                u.setEnabled(true);
                v.setEnabled(true);
                w.setEnabled(true);
                x.setEnabled(true);
                y.setEnabled(true);
                z.setEnabled(true);
        public void communicate()
            // The connection has been established - now send/receive.
            try
                //  create channels
                out = new ObjectOutputStream(server.getOutputStream());
                out.flush();
                in = new ObjectInputStream(server.getInputStream());
            catch (IOException ioe)
                JOptionPane.showMessageDialog(null,"IO Exception: " + ioe.getMessage());
            catch (NullPointerException n)
                JOptionPane.showMessageDialog(null,"Error occured...");
        public void processClient()
            try
                // Tells server which category is selected by user
                out.writeObject(categorySelected);
                out.flush();
                secret = (String)in.readObject();
                length = (Integer)in.readObject();
                lines = "";
                for (int x=0;x < length;x++)
                    lines += " - ";
                answer.setText(lines);
                String ToDisplay=""; 
                  for (int q=0; q<secret.length;q++)
                   ToDisplay+=secret.length;
                   answer.setText(" " + ToDisplay); */
                  // String Correctin = (String)in.readObject();
                  // JOptionPane.showMessageDialog(null, Correctin );
            catch (IOException ioe)
                 JOptionPane.showMessageDialog(null, "IO Exception: " + ioe.getMessage());
            catch (ClassNotFoundException cnfe)
                JOptionPane.showMessageDialog(null, "Class not found..." );
        }//end method
        public void sendGuess()
            try
                // Sends the character guessed by user
                out.writeObject(guess);
                out.flush();
                // Chances incremented
                //chances = chances + 1;
                // Calcualates to see whether chances are up
                //if (chances >= 7)
                //    JOptionPane.showMessageDialog(null,"GAME OVER!! You used up all your chances...");
                 //   disableButtons();
            }//end try
            catch (IOException ioe)
                JOptionPane.showMessageDialog(null, ioe.getMessage());
            }//end catch
        }//end method
        public static void main(String[] args)
            ClientApp client = new ClientApp();
            client.communicate();
            client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            client.setSize(500,300);
            client.setVisible(true);     
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    public class ServerApp
         String movies [] = {"shrek","titanic","disturbia","blade","scream"};
         String sport [] = {"tennis","golf","rugby","hockey","soccer","judo"};
         int inCategory; // Category Selected By User
         int selectw; // Random word selected in Array
         String secretword = "";
         int wordlength = 0;
         String guess;
         char letter;
         Random rand = new Random();
         String msg;
         ObjectOutputStream out;
         ObjectInputStream in;
         int chances;
        // Server socket
        private ServerSocket listener;
        // Client connection
        private Socket client;
        public ServerApp()
           // Create server socket
            try {
                listener = new ServerSocket(8008);
            catch (IOException ioe)
              JOptionPane.showMessageDialog(null,"IO Exception: " + ioe.getMessage());
        public void listen()
            // Start listening for client connections
            try
              client = listener.accept(); 
              System.out.println("Server started");       
              processClient();
            }//end try
            catch(IOException ioe)
                JOptionPane.showMessageDialog(null,"IO Exception: " + ioe.getMessage());
            }//end catch   
        public void processClient()
            try
                while(msg != "TERMINATE")
                   //input and output stream
                   out = new ObjectOutputStream(client.getOutputStream());
                   out.flush();
                   in = new ObjectInputStream(client.getInputStream());        
                   //Receiving a category
                   inCategory = (Integer)in.readObject();
                   chances = 7;
                   selectw = 0;
                   if (inCategory == 0)
                        selectw = rand.nextInt(5);
                        secretword = movies[selectw];
                        out.writeObject(secretword);
                        out.flush();
                    }//end if
                    if (inCategory == 1)
                        selectw = rand.nextInt(6);
                        secretword = sport[selectw];
                    }//end if
                        wordlength = secretword.length();
                        out.writeObject(wordlength);
                        out.flush();
                           for (int y=0;y < wordlength;y++)
                                guess = (String)in.readObject();
                                letter = guess.charAt(0);
                                  if(chances == 0)
                                      JOptionPane.showMessageDialog(null,"No more chances left");
                                   else
                                  if(letter == secretword.charAt(y))
                                    JOptionPane.showMessageDialog(null,"You chose a correct letter...");
                                else
                                    JOptionPane.showMessageDialog(null,"You chose a wrong letter...");
                                    chances--;
                        JOptionPane.showMessageDialog(null,"You won the game...");
                }//end while
                // Step 3:close down
                out.close();
                in.close();
                client.close();
                System.out.println("Server stopped");
            catch (IOException ioe)
                JOptionPane.showMessageDialog(null,"IO Exception: " + ioe.getMessage());
            catch (ClassNotFoundException cnfe)
                JOptionPane.showMessageDialog(null,"Class not found: " + cnfe.getMessage());
        public static void main(String[] args)
            // Create application
            ServerApp server = new ServerApp();
            // Start waiting for connections
            server.listen();
    }

    JAVAHELPNEEDED wrote:
    How do I save that amount of code?
    Can you HELP me or NOT??Depends what you mean. Will I write you any code? No. Will I tell you what to write? No. You can do it yourself, that's why it's called your homework. I will, though, give you a couple of tips on how to get started.
    1) Throw away what you've done
    2) Do a quick requirements analysis. That means, write down descriptive, plain English (or whatever language you think in) what the thing is supposed to do. "Be a hangman game" is too brief, but twenty pages of technical jargon is too much. Write a bit of a story about what the program must do. You now have the start of a design.
    3) Break down what has to be done into manageable chunks. Your first mistake (and most newbs) was trying to write one side of the game in a single class. Don't be afraid to write 20 classes, or 50, if that's what's needed. It'll be easier both now and in the long run
    4) Tackle each chunk one by one. Don't try and do it all at once, that never works. If you write the code one bit at a time, you'll inevitably write more modular code
    5) You'll probably screw it up. Don't worry. It happens. Try again
    6) Don't give up. Writing software is hard, there's no way around that, so deal with it
    7) Don't make the mistake of thinking the software is the GUI. It isn't (don't extend JFrame, hint hint)
    8) Good luck

  • Hangman game - logic problem

    Hello, im trying to make it so that when an incorrect letter is chosen (arrayToPass does not contain string) the picture of the hangman is drawn.
    I want count to go up to the number of incorrect attempts so that the appropriate picture is shown - not sure where I would put this though (count).
    Generaly having trouble understanding the logic for this.
    Please give some hints
    Commented out code is various stuff ive tried already and i did not see a forum for logic therefore i think this is right.
         public void actionPerformed(ActionEvent e)
              boolean b = false;
              int count = 0;
              ImageIcon icon = null;
              String s = e.getActionCommand();
              String string = s.toLowerCase();
              b = arrayToPass.indexOf(string) > -1; //Sees if array word has letter in radiobutton in it
              //Split the word into an array
              char[] chr = arrayToPass.toCharArray();
              if(b == true) //If the word holds that letter
                   //String tempString = new Character(chr[1]).toString();
                   //jtp.setText("Correct");
                   for(int k = 0; k < chr.length; k++)
                        String ss = new Character(chr[k]).toString();
                        jl.setText(ss); //Set label to correct letter found
              else
                   count++;
                   if(count == l)
                        icon = new ImageIcon("E:\\HangMan1.jpg");
                        jtp.insertIcon(icon);
                   else if(count == 2)
                        icon = new ImageIcon("E:\\HangMan2.jpg");
                        jtp.insertIcon(icon);
                   else if(count == 3)
                        icon = new ImageIcon("E:\\HangMan3.jpg");
                        jtp.insertIcon(icon);
                   else if(count == 4)
                        icon = new ImageIcon("E:\\HangMan4.jpg");
                        jtp.insertIcon(icon);
                   else if(count == 5)
                        icon = new ImageIcon("E:\\HangMan5.jpg");
                        jtp.insertIcon(icon);
         }

    Although this is still very simple code, it always pays off to bring structure into your code.
    You have a couple of tasks which you have to fulfill here.
    1) Analyze the game situation.
    2) change your game state accordingly.
    3) display your current game state.
    You can handle these three tasks completely seperate. First, you have to check for your words' validity. Depending on this, you have to change your count. Then, you have to repaint.
    So, what you need is at least a game state object. This one must live as long as the game lives, so fields like your "count" are defintely wrong inside the "actionPerformed" method. Don't misuse the Action Command to carry information. Allow access to your game state object, and store the hangman word there.
    Your word validity check is quite complicated. Maybe it would be a good idea to move it into its own method.
    Your painting method will contain more than just changing your hangman pics. For example, you also have to uncover letters that were hidden before, so maybe you should put this into this method, as well.
    This might look like overkill, but seperating helps you to distinguish between good code and wrong code. It also helps you to mentally concentrate on one specific topic, instead of handling everything as one mesh.

  • Simple Hangman

    Hi,
    As the title suggest im putting together a simple hangman program. Ive been learning java for about a month now and I'm 90% done with the homework. The problem im having is actually outputting the correct slected letters to the screen. Im not trying to get game made for me, its just annoying that ive got all the core components worked out, i just cant output correct guesses to the screen :). For example.
    I have created an array of 26 buttons, A-Z with this loop.
    StringBuffer buffer;
              letters = new Button[26];
              for (i = 0; i <26; i++)
                   buffer = new StringBuffer();
                        buffer.append((char) (i+65));
                        letters[i] = new Button (buffer.toString());
                        letters.addActionListener( this );
                   add(letters[i]);
              }The below segment is what im using to distinguish between correct and incorrect guesses.
    {code:java}     public void actionPerformed( ActionEvent ev)
    for (i = 0; i < 26; i++)
         if (ev.getSource() == letters)
         letters[i].setVisible(false);
         if (Words[rnd].indexOf(ev.getActionCommand()) == -1)
              ++badguesses;
              System.out.print("Incorrectguesses is: ");
              System.out.println(badguesses);
              repaint();
         if(Words[rnd].indexOf(ev.getActionCommand()) >= 0)
              ++correctguesses;
              letterbuffer.insert(Words[rnd].indexOf(ev.getActionCommand()),ev.getActionCommand());
         repaint();
              }As you can see, im trying to add the letter pressed (button) to a stringbuffer, so i can send it down to the paint method. This compiles. However. From what i understand, (and i want to understand) java is adding the letters into a single string so, "f""i""r""e" would become "fire". Is this correct? My problem is outputting the individual characters. I had got to:
    {code:java}public void paint(Graphics graf)
    if (correctguesses > 0){
              for (i = 1; i <=length; i++)
                   graf.drawString(letterbuffer.charAt(i),85,85+30*i);
                   //repaint();
              } When i realised that this wasnt going to work. Basically i have no idea how to outprint the individual characters to their respective slots(check measurements in drawstring). Could somone explain what is going on, and suggest a possible fix please :)
    Regards, D4rky
    Here are my variables:String[] Words = {lots of words in here   :)  };
    Random rand = new Random();
    int rnd =(int)Math.floor(Math.random()*Words.length);
    int length = Words[rnd].length(); //Length of chosen Array
    int badguesses = 0;
    int correctguesses = 0;
    int x;
    int i;
    Button letters[];
    StringBuffer letterbuffer = new StringBuffer(length);{code}Edited by: D4rky on Nov 1, 2009 11:20 AM
    Edited by: D4rky on Nov 1, 2009 11:22 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    [Be Forthright When Cross Posting To Other Sites|http://faq.javaranch.com/java/BeForthrightWhenCrossPostingToOtherSites]:
    [http://forums.devshed.com/java-help-9/hangman-650502.html]
    ~

Maybe you are looking for

  • Credit data inconsistency

    Dear Experts ! Please help me in the below credit management scenario. User observed some inconsistent data in transaction -VKM1 with respect to the FD33 screen . I checked the data in RVKRED88 report and found that open order value of the sales orde

  • Incoming/Outgoing Excise Invoice

    What information should be maintained for following fields that appear under Header:- Excise Ref.no., Excise Ref Date & Excise Removal Time. also when I am trying to post an incoming excise invoice it says "no match record found "GL Account" (OACT) O

  • Bridge opens into microsoft works

    I need some help. I installed Photoshop CS5 yesterday and it was working fine, so today I deleted CS3, now when i try to open a photo from Bridge it opens into Microsoft Works instead of Photoshop, if I right click and go to 'open with' Photoshop is

  • When using external speakers, they won't unmute

    I am using a U530 Touch with Realtek HD Audio driver version 6.0.1.7535 and Windows 10 build 10240. When using external speakers, everything works fine, except when I mute speakers they will not unmute without unplugging the 3.5 mm speaker jack and p

  • Weird resizing bug with Fluxbox + Xcompmgr.

    I'm using fluxbox and xcompmgr today, trying it out again after a while with openbox. Every time I resize a window, it seems like xcompmgr is failing to resize the dropshadow it leaves behind it, or other times it will just show the contents of the w