8 Replies - 863 Views - Last Post: 30 March 2010 - 04:47 PM Rate Topic: -----

#1 croog24  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 39
  • Joined: 04-February 10

Replacing Characters in a String

Posted 28 March 2010 - 05:18 PM

The concept of this program is based off a Hangman game. I have the user entering a letter in a JFrame, and want to replace any of the X's with that letter that would go with the word. (Sorry if that's confusing, couldn't figure out how to explain it, but it's hangman so I think you get the idea).

Here is what I have so far...
Random rand= new Random();
        
        String hidden="XXXXXXX";
        String word="";
        int count=1;
        while(count==1)
        {
          int subCount=rand.nextInt(5);
            if(subCount==0)
            {
                word="ornament";
            }
            else if(subCount==1)
            {
                word="chimney";
            }
            else if(subCount==2)
            {
                word="reunion";
            }
            else if(subCount==3)
            {
                word="snowman";
            }
            else if(subCount==4)
            {
                word="present";
            }
            else if(subCount==5)
            {
                word="holiday";
            }

          String s=JOptionPane.showInputDialog("Enter a letter guess: ");
          
          if(word.contains(s))
          {
              
          }
        }



I think that is what I'm suppose to do, so if it is, I don't know what to put under the if statement to replace any letters.

Is This A Good Question/Topic? 0
  • +

Replies To: Replacing Characters in a String

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,050
  • Joined: 15-July 08

Re: Replacing Characters in a String

Posted 28 March 2010 - 08:10 PM

Before I answer your question, let me help you simplify much of this code by using an array:
    // Make an array.
    String[] words = {"ornament", "chimney", "reunion", "snowman", "present", "holiday"};

          ...
          //The 5 is NOT the maximum value, it is the value ABOVE the
          // maximum value...so you want 6 here, not 5
          int subCount=rand.nextInt(6);
          
          // Now grab that word.
          word = words[subCount];



And for the replacement, what you can do is to is use the indexOf() method to find the location of a character (-1 if it doesn't exist in the string), and then replace that index with a new character. The API will help you here.
Was This Post Helpful? 0
  • +
  • -

#3 kingfeanor  Icon User is offline

  • D.I.C Head

Reputation: 44
  • View blog
  • Posts: 60
  • Joined: 18-April 09

Re: Replacing Characters in a String

Posted 28 March 2010 - 08:13 PM

In java strings are immutable meaning you can't actually edit them. You can use the String's substring method to piece the string together or you can use the StringBuilder class to edit a character sequence in place.
Was This Post Helpful? 1
  • +
  • -

#4 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,050
  • Joined: 15-July 08

Re: Replacing Characters in a String

Posted 28 March 2010 - 08:28 PM

Yep, actually, he's right, A StringBuffer would be useful to store the "current" string in (The one with all the ____'s). It makes things a heck of a lot easier. Here is the API: http://java.sun.com/...ringBuffer.html
Was This Post Helpful? 0
  • +
  • -

#5 zim1985  Icon User is offline

  • Grand Inquisitor
  • member icon

Reputation: 74
  • View blog
  • Posts: 568
  • Joined: 19-February 10

Re: Replacing Characters in a String

Posted 29 March 2010 - 01:31 AM

Dogstopper's suggestion with the StringBuffer would be easiest.

You could use the String's toCharArray() method. You could do something like:
String str = "Example";
ch[] letters = str.toCharArray();

for(int i = 0; i < letter.length; i++)
{
    if(letters[i] == 'E')
    {
        letters[i] == 'A';
    }
}


Of course you could change the letters as needed.

This post has been edited by zim1985: 29 March 2010 - 01:41 AM

Was This Post Helpful? 0
  • +
  • -

#6 croog24  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 39
  • Joined: 04-February 10

Re: Replacing Characters in a String

Posted 29 March 2010 - 07:17 AM

All great ideas, unfortunately we have not "learned" about arrays and StringBuffers in class yet so we are not allowed to use any of it. Is there a way using the indexOf() method where I can store the index values from String word and replace the corresponding index values of the "XXXXXXX".
Was This Post Helpful? 0
  • +
  • -

#7 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Replacing Characters in a String

Posted 29 March 2010 - 07:27 AM

What you will have to do in this situation is make a loop to cycle through the hidden word and what they have guess and use charAt() method, or the indexOf method. Then use the Substring method to get the first part of the word and second part and save it as part1 and part2,now its pretty simple.
String hiddenWord = part1 + guessedletter + part2;

Hope this helps!


Edit - Seems apparent can only use String class to do this for that is probably close to all he knows in the possible ways to do this. All methods I named above are in the String class and here is the link to the API that you can use to see examples of how to use a method and what methods you can use.
String API

This post has been edited by Fuzzyness: 29 March 2010 - 07:42 AM

Was This Post Helpful? 1
  • +
  • -

#8 zim1985  Icon User is offline

  • Grand Inquisitor
  • member icon

Reputation: 74
  • View blog
  • Posts: 568
  • Joined: 19-February 10

Re: Replacing Characters in a String

Posted 29 March 2010 - 10:33 AM

Though more tedious, the above method is what you will be looking for.
Was This Post Helpful? 0
  • +
  • -

#9 croog24  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 39
  • Joined: 04-February 10

Re: Replacing Characters in a String

Posted 30 March 2010 - 04:47 PM

So I believe I got the hidden word working, thank you everyone for your help with that. Here is the ALMOST final product of the hangman game.

Last 3 problems:
1) How do I clear all graphics in the window for when I start another round? I've tried something called removeAll() but that did not work.

3) I'm not sure where or how to put String s in a position where it will not come up if the user has won. I tried something such as:
if(hidden.contains("X"))


But that isolates the String S and the rest of the program can no longer use it.

Anyway here is the program:

import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Main
{
    public static void main(String[] args)
    {
        JFrame frame=new JFrame();
        frame.setSize(800, 800);
        frame.setTitle("Hangman");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        HangComponent c=new HangComponent();
        frame.add(c);
        frame.setVisible(true);

        Random rand= new Random();

        String word="";
        int count=0;
        while(count==0)
        {
          int subCount=rand.nextInt(6);
            if(subCount==0)
            {
                word="yultide";
            }
            else if(subCount==1)
            {
                word="chimney";
            }
            else if(subCount==2)
            {
                word="candles";
            }
            else if(subCount==3)
            {
                word="rudolph";
            }
            else if(subCount==4)
            {
                word="miracle";
            }
            else if(subCount==5)
            {
                word="holiday";
            }

          String hidden="XXXXXXX";

          for(int i=0; i<=10; i++)
          {
              if(i<10)
           {
          String s=JOptionPane.showInputDialog("Your word is "+hidden+" Enter a " +
                  "letter guess: ");

          //If user has won
          if(!hidden.contains("X"))
            {
              String s2=JOptionPane.showInputDialog("You have won! Would you " +
                      "like to play again? (y/n)");
              if(s2.equals("y"))
                  hidden="XXXXXXX";
              if(s2.equals("n"))
                  count=1;
              break;
            }

          //If a correct guess
          if(i<10 && word.contains(s))
          {
              int index=word.indexOf(s);
              String part1=hidden.substring(0, index);
              String part2=hidden.substring(index, 6);
              hidden=part1+s+part2;
          }

          //If an incorrect guess
          else if(i<=0 && !word.contains(s))
           {
              c.setbase();
              c.repaint();
           }
          else if(i<=1 && !word.contains(s))
           {
              c.setmiddle();
              c.repaint();
           }
          else if(i<=2 && !word.contains(s))
           {
              c.setrope();
              c.repaint();
           }
          else if(i<=3 && !word.contains(s))
           {
              c.sethead();
              c.repaint();
           }
          else if(i<=4 && !word.contains(s))
           {
              c.setneck();
              c.repaint();
           }
          else if(i<=5 && !word.contains(s))
           {
              c.setbody();
              c.repaint();
           }
          else if(i<=6 && !word.contains(s))
           {
              c.setleftArm();
              c.repaint();
           }
          else if(i<=7 && !word.contains(s))
           {
              c.setrightArm();
              c.repaint();
           }
          else if(i<=8 && !word.contains(s))
           {
              c.setleftLeg();
              c.repaint();
           }
          else if(i<=9 && !word.contains(s))
           {
              c.setrightLeg();
              c.repaint();
           }
         }

          //If user has lost the game
          else if(i==10)
           {
              String s3=JOptionPane.showInputDialog("You have lost! Would you " +
                      "like to play again? (y/n)");
              
              if(s3.equals("y"))
                  hidden="XXXXXXX";

              if(s3.equals("n"))
                  count=1;
           }
          
        }
        }
      }

    }



import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;

public class HangComponent extends JComponent
{
    private boolean base=false;
    private boolean middle=false;
    private boolean rope=false;
    private boolean head=false;
    private boolean neck=false;
    private boolean body=false;
    private boolean leftArm=false;
    private boolean rightArm=false;
    private boolean leftLeg=false;
    private boolean rightLeg=false;

    public void paintComponent(Graphics g)
    {

        //Recover Graphics 2D
        Graphics2D g2= (Graphics2D) g;
        
        //Base of the gallow
        if(base)
            g2.drawLine(400, 600, 750, 600);

        //Stand of the gallow
        if(middle)
        {
            g2.drawLine(700, 600, 700, 100);
            g2.drawLine(700, 100, 415, 100);
        }

        //Rope
        if(rope)
            g2.drawLine(415, 100, 415, 200);

        //Head
        if(head)
            g2.drawOval(400, 200, 30, 40);

        //Neck
        if(neck)
            g2.drawRect(411, 240, 7, 15);

        //Body
        if(body)
            g2.drawRect(397, 255, 35, 60);

        //Left Arm
        if(leftArm)
            g2.drawLine(397, 255, 350, 297);

        //Right Arm
        if(rightArm)
            g2.drawLine(432, 255, 470, 297);

        //Left Leg
        if(leftLeg)
            g2.drawLine(397, 315, 397, 400);

        //Right Leg
        if(rightLeg)
            g2.drawLine(432, 315, 432, 400);
    }
    public void setbase(){base=true;}
    public void setmiddle(){middle=true;}
    public void setrope(){rope=true;}
    public void sethead(){head=true;}
    public void setneck(){neck=true;}
    public void setbody(){body=true;}
    public void setleftArm(){leftArm=true;}
    public void setrightArm(){rightArm=true;}
    public void setleftLeg(){leftLeg=true;}
    public void setrightLeg(){rightLeg=true;}
}



EDIT: I took out problem #2. Don't know why I couldn't get that one fixed myself earlier...

This post has been edited by croog24: 30 March 2010 - 08:02 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1