Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 22 of 22

Thread: For loop to create string.

  1. #1
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default For loop to create string.

    Hi, i'm trying to do a hangman game for my home task, and i got a few problems
    the first problem is: How can i return a string from for loop?

    Here is what i got so far:
    for (int i = 0; i < userWord.length(); i++) {
      if (userGuess.equals(Character.toString(userWord.charAt(i)))) {
         System.out.print(userGuess.toUpperCase() + " ");
      } else {
        System.out.print("_ ");
      }
    }

    When the userWord is "apple" and userGuess is "a" then it prints " A _ _ _ _ ",
    the next time user guess something for example "w" it prints " _ _ _ _ _ "


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: For loop to create string.

    I'm assuming you aren't using arrays yet, and that's fine. If you are and would like to explore that approach, say so. For an approach that doesn't use an array, then the current result will change from:

    "_ _ _ _ _"

    to

    "A _ _ _ _"

    then when 'w' is guessed the current result will remain unchanged,

    "A _ _ _ _"

    So compare each character in the word to be guessed with the user's guess and fill in any correct guesses in the current result. The currentResult is a String object (which is immutable, by the way) that changes each time a correct guess is made. You can use the String methods to make this happen, so review the String API page.

  3. #3
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: For loop to create string.

    I'm familiar with arrays and all the tried letters are saved to ArrayList. With a little help from my dear friend google, i came up with this:
    		for (int i = 0; i < userWord.length(); i++) {
    			for (String a : allLetters) {
    			if (a.equals(Character.toString(userWord.charAt(i)))) {
    				System.out.print(a.toUpperCase() + " ");
    			} 
    			if (!a.equals(Character.toString(userWord.charAt(i)))) {
    				System.out.print("_ ");
    			}
    		}	
    		}
    		System.out.println();
    	}
    Then this is the result:
    All the letters: [A, P, L, E] ( i print this out just for test )
    A _ _ _ _ P _ _ _ P _ _ _ _ L _ _ _ _ E
    now i get messed up word i'm thinking i must take the "sysout("_ ") out from the second for loop ? if so, then how ?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: For loop to create string.

    If the condition in the second if is the negative of the condition in the first if, the code should use an else:
      if (x == 6} {
        //  do this
      }
      if (x != 6) {  //  this statement is confusing and could be an error
        // do that
      }
     
    //  vs
     
      if (x == 6) {
        // do this
      } else {       // this is clearer  and won't be an error
       // do that
      }
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: For loop to create string.

    Thank you Norm for clearing that for me, but the end result stays the same as before.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: For loop to create string.

    Can you post an example of what the code outputs now and an example of what you want the output to be.
    For example:
    Current: A____
    Desired: Ax___
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: For loop to create string.

    When i try to guess word "apple" then everytime i guess a letter the "_" adds in that word..
    my current output is : A _ _ P _ P _ _ _ _ "
    but what i desire is : "A P P _ _ "

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: For loop to create string.

    Can you make a small, complete program that compiles and executes for testing? It just needs to define allLetters and userWord and nothing else and then use the nested for loops in post#3
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: For loop to create string.

    Here is the small program [Java] help - Pastebin.com , tho i'm using TextIO to make user input easier.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: For loop to create string.

    Sorry, I don't go to other sites, can you post the code for a small test program here? Make a small testing program, Not the full program you are working on.

    Can you explain when you want to print a letter and when print a "-"?

    The inner loop will always print something for all the letters in allLetters.
    If there are 26 letters, the inner loop will print 26 times.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: For loop to create string.

    public class Test {
     
            public static ArrayList<String> allLetters = new ArrayList<String>();
            public static String userWord, userGuess;
     
            public static void main(String[] args) {
                    System.out.println("userWord");
                    userWord = TextIO.getlnString().toUpperCase();         
                    boolean game = true;
                    while (game == true) {
                            System.out.println("userGuess");
                            userGuess = TextIO.getlnString().toUpperCase();
                            allLetters.add(userGuess);
                            test();
                    }
     
            }
     
            public static void test() {
                    for (int i = 0; i < userWord.length(); i++) {
                            for (String t2heke : allLetters) {
                                    if (t2heke.equals(Character.toString(userWord.charAt(i)))) {
                                            System.out.print(t2heke.toUpperCase() + " ");
                                    } else {
                                            System.out.print("_ ");
                                    }
                            }
                    }
                    TextIO.putln();
            }
    }

    (I'm using TextIO for easier input) I want to print letter when user guesses the right letter and the "_" when the letter doesnt match the one in word.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: For loop to create string.

    Please add code that assigns values to the userWord and the allLetter variables so the code can be compiled and executed WITHOUT needing any user input. The code should contain all that is needed to be able to call the test() method.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: For loop to create string.

    public class Test {
     
    	public static ArrayList<String> allLetters = new ArrayList<String>();
    	public static String letters[] = { "p", "e", "l", "a", "c", "d" };
    	public static String userWord, userGuess;
     
    	public static void main(String[] args) {
    		userWord = "apple";
    		System.out.println("userWord is: " + userWord);
    		for (int i = 0; i < letters.length; i++) {
    			userGuess = letters[i];
    			System.out.println("userGuess is: " + userGuess.toUpperCase());
    			allLetters.add(userGuess);
    			test();
    		}
    	}
     
    	public static void test() {
    		for (int i = 0; i < userWord.length(); i++) {
    			for (String t2heke : allLetters) {
    				if (t2heke.equals(Character.toString(userWord.charAt(i)))) {
    					System.out.print(t2heke.toUpperCase() + " ");
    				} else {
    					System.out.print("_ ");
    				}
    			}
    		}
    		System.out.println();
    	}
    }

    right now the userWord is "apple" and the userGuess is taken from string array called letters
    I'm sorry if this is not the program you wanted :\

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: For loop to create string.

    Can you explain when you want to print a letter and when print a "-"?

    There should be one character printed for each letter in userWord. The inner loop should only print ONE character: either the letter or a "-". The logic needs to be changed so that only one character is printed.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: For loop to create string.

    public class Test {
     
    	public static ArrayList<String> allLetters = new ArrayList<String>();
    	public static String letters[] = { "p", "e", "l", "a", "c", "d" };
    	public static String userWord, userGuess;
            public static boolean found;
     
    	public static void main(String[] args) {
    		userWord = "apple";
    		System.out.println("userWord is: " + userWord);
    		for (int i = 0; i < letters.length; i++) {
    			userGuess = letters[i];
    			System.out.println("userGuess is: " + userGuess.toUpperCase());
    			allLetters.add(userGuess);
    			test();
    		}
    	}
     
    	public static void test() {
    		for (int i = 0; i < userWord.length(); i++) {
                              found = true;
    			for (String t2heke : allLetters) {
    				if (t2heke.equals(Character.toString(userWord.charAt(i)))) {
    					System.out.print(t2heke.toUpperCase() + " ");
                                              found = false;
    				} 
    			}
                                  if (found) {
                                    System.out.print("_ ");
                               }
    		}
    		System.out.println();
    	}
    }

    if i add boolean found in it and do the following then it works, but why and how? is there another way to do this ?

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: For loop to create string.

    That looks like it does what you want. Why are you asking for another way to do it? That looks like a good way.

    The inner loop is a search loop. You only want a "-" to print if no match is found. To remember if a match was found the code uses a boolean.
    Normal English would use the variable found differently. Initialize it to false and set true when the match is found. If Not found, then print the "-"

    The variable would be named: noMatch for the way the code uses it.
    If you don't understand my answer, don't ignore it, ask a question.

  17. The Following User Says Thank You to Norm For This Useful Post:

    clyxee (December 11th, 2013)

  18. #17
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: For loop to create string.

    It was pretty confusing, that's why i asked if there's other ways to do it Thank you Norm
    Now i have another question: How can i compare the end result with the original word, to stop the game ?

  19. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: For loop to create string.

    Build a String in addition to printing the letters/"-" and compare it to the word.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #19
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: For loop to create string.

    How should i do that ? give a string and then replace letters or how ?

  21. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: For loop to create string.

    One easy way is to use concatenation:
    String x = ""; // Define empty String
    ...

    x += "-"; // build String using concatenation
    If you don't understand my answer, don't ignore it, ask a question.

  22. The Following User Says Thank You to Norm For This Useful Post:

    clyxee (December 12th, 2013)

  23. #21
    Junior Member
    Join Date
    Dec 2013
    Location
    Estonia
    Posts
    18
    My Mood
    Happy
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: For loop to create string.

    Oh my god i got it Thank you so much Norm !!

  24. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: For loop to create string.

    Glad you got it working.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Create JRadioButtons from HashMap by loop
    By poundnmonitor in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 30th, 2013, 09:00 AM
  2. loop help need to create the letter L AND Y
    By YG N JYP FAM4EVA in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 26th, 2013, 01:56 PM
  3. Trying to create an alphabet-only string of any length
    By skw4712 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 19th, 2012, 06:39 AM
  4. I need to create a certain SHAPE with FOR LOOP.
    By Rage1337 in forum What's Wrong With My Code?
    Replies: 8
    Last Post: August 4th, 2012, 09:15 AM
  5. Create a CLOB object with the string value
    By oshoarun in forum JDBC & Databases
    Replies: 0
    Last Post: March 6th, 2010, 02:54 AM