39065

hangman picture isn't changing

I'm busy writing an hangman application and I'm currently checking if some of the code works... now i haven't gotten to hiding the word part yet so in the place of that code i used an if statement as supplementary code:

if(original.indexOf(button.getText())!=-1){ JOptionPane.showMessageDialog(null, "Your word does contain" + text ); } else{ JOptionPane.showMessageDialog(null, "There is no" + text ); error++; } }

Anyway when I press the buttons that's not in the word it suppose to add to my errors according to

error++;

and it only finds the first letter in the word. One of my words are Dinosaur when i press D it says "Yes, there is a D" but when I press A it says "No, there is no I" where the clearly is

Can someone please help

here's my full code

import java.awt.*; import java.awt.event.*; import java.util.Arrays; import javax.swing.*; import java.io.*; import java.util.ArrayList; import java.util.Random; import java.util.List; public final class Hangman extends JFrame implements ActionListener{ String original = readWord(); int error = 0; String imageName; JButton btnAddWord = new JButton("Add New Word"); JButton btnRestart = new JButton("Restart"); JButton btnHelp = new JButton("Help"); JButton btnExit = new JButton("Exit"); JLabel word = new JLabel(original); static JPanel panel1 = new JPanel(); static JPanel panel2 = new JPanel(); static JPanel panel3 = new JPanel(); static JPanel panel4 = new JPanel(); public Hangman(){ Container content =getContentPane(); content.setLayout(new GridLayout(0,1)); if(error >= 0) imageName = "hangman1.jpg"; if(error >= 1) imageName = "hangman2.jpg"; if(error >= 2) imageName = "hangman3.jpg"; if(error == 3) imageName = "hangman4.jpg"; if(error == 4) imageName = "hangman5.jpg"; if(error == 5) imageName = "hangman6.jpg"; if(error == 7) imageName = "hangman7.jpg"; ImageIcon icon = null; if(imageName != null){ icon = new ImageIcon(imageName); } JLabel image = new JLabel(); image.setIcon(icon); btnAddWord.addActionListener(this); btnRestart.addActionListener(this); btnHelp.addActionListener(this); btnExit.addActionListener(this); panel2.add(image); panel3.add(word); panel4.add(btnAddWord); panel4.add(btnRestart); panel4.add(btnHelp); panel4.add(btnExit); for(char i = 'A'; i <= 'Z'; i++){ String buttonText = new Character(i).toString(); JButton button = getButton(buttonText); panel1.add(button); } } public JButton getButton(final String text){ final JButton button = new JButton(text); button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(original.indexOf(button.getText())!=-1){ JOptionPane.showMessageDialog(null, "Your word does contain " + text ); } else{ JOptionPane.showMessageDialog(null, "There is no " + text ); error++; } } }); return button; } public String readWord(){ try{ BufferedReader reader = new BufferedReader(new FileReader("Words.txt")); String line = reader.readLine(); List<String> words = new ArrayList<String>(); while(line != null){ String[] wordsLine = line.split(" "); boolean addAll = words.addAll(Arrays.asList(wordsLine)); line = reader.readLine(); } Random rand = new Random(System.currentTimeMillis()); String randomWord = words.get(rand.nextInt(words.size())); return randomWord; }catch (Exception e){ return null; } } public void actionPerformed(ActionEvent e){ if(e.getSource() == btnAddWord){ try{ FileWriter fw = new FileWriter("Words.txt", true); PrintWriter pw = new PrintWriter(fw, true); String word = JOptionPane.showInputDialog("Please enter a word: "); pw.println(word); pw.close(); } catch(IOException ie){ System.out.println("Error Thrown" + ie.getMessage()); } } if(e.getSource() == btnRestart){ } if(e.getSource() == btnHelp){ String message = "The word to guess is represented by a row of dashes, giving the number of letters and category of the word." + "\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions." + "\nIf the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark." + "\n" + "\nThe game is over when:" + "\nThe guessing player completes the word, or guesses the whole word correctly" + "\nThe other player completes the diagram"; JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE); } if(e.getSource() == btnExit){ System.exit(0); } } public static void main (String [] args){ Hangman frame = new Hangman(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 600); frame.add(panel1, BorderLayout.NORTH); frame.add(panel2, BorderLayout.CENTER); frame.add(panel3, BorderLayout.SOUTH); frame.add(panel4, BorderLayout.SOUTH); } }

Answer1:

My first guess is that your text comparison is case sensitive.

"Dinosaur".indexOf("A") is not the same as "Dinosaur".indexOf("a")

I'd suggest converting the text to common case when you compare it.

original.toLowerCase().indexOf(button.getText().toLowerCase())!=-1

Answer2:

This is because you're not correctly checking whether the word that you're reading from the file is in the same case as the text in your JButton. There're a couple of ways to fix this:

<ol> <li>

As @MadProgrammer suggested. Have a couple of checks to cover both lowercase and uppercase characters.

</li> <li>

Standardizing your List<String> words i.e. keep everything in one case when you're reading from the file. That way you don't have to worry much in terms of checking whether its in lowercase or uppercase. So in this case you might want to change: String[] wordsLine = line.split(" "); to String[] wordsLine = line.toLowerCase().split(" "); or String[] wordsLine = line.toUpperCase().split(" "); (depending on which one you're comfortable with). Then your check with a single indexOf() operation looks fine.

</li> </ol>

Recommend

  • I am trying to write a program that will keep track of a players wins everything works except can an
  • Calculate the number of dollars, quarters, dimes, nickels, an pennies with random amount of pennies
  • VB Program Array of Structure and Class
  • Adding the same Panel to multiple TabPages
  • watershed function provided by EmguCv
  • key listener not working for some reason
  • create images clickable on jpanel
  • How to create vertical TitledBorder in JPanel (javax swing)
  • JButton background images
  • Error ::Invalid token '=' in class, struct, or interface member declaration
  • Aligning and Inlining components (or icons) in JTextPane
  • Are there any issues with placing image as background on an extended JFrame?
  • Syntax error on tokens, AnnotationName expected instead - error on query
  • JSR-330 support in Picocontainer : @Inject … @Named(\"xxx)
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • How can I display the parent menu item's description using Wordpress walkers?
  • Selenium to click on a javascript button corresponding to a text
  • IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
  • Simulate click Geckofx vb,net
  • IE7 and TinyMCE with Plone
  • Using JRuby with Rails 3.2
  • How to view images from protected folder with php?
  • Code in Job's Script Block after Start-Process Does not Execute
  • Moving Android View and preventing onDraw to be called over and over again
  • MonoTouch: How to download pdf incrementally as indicated in the Apple slides “Building Newsstand Ap
  • How to have background script and something similar to a default popup?
  • Swing - Get new component under mouseReleased
  • How to attach a node.js readable stream to a Sendgrid email?
  • Listbox within Listbox and scrolling trouble in Windows Phone 7 Silverlight
  • Problems to linebreak with an int in JLabel
  • Align navbar back button on right side
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • Obtain ObjectIdHex value from mgo query
  • sending/ receiving email in Java
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • How to delete a row from a dynamic generate table using jquery?
  • Proper way to use connect-multiparty with express.js?
  • Load html files in TinyMce
  • Free memory of cv::Mat loaded using FileStorage API
  • Checking variable from a different class in C#