1

How can I print out dashes "-" in the same length as the word length? I used for-loop but only got 1 dash.

    for(int i=0; i<secretWordLen; i++) theOutput = "-";

Main:

public String processInput(String theInput) {
    String theOutput = null;

    String str1 = new String(words[currentJoke]);
    int secretWordLen = str1.length();

    if (state == WAITING) {
        theOutput = "Connection established.. Want to play a game? 1. (yes/no)";
        state = SENTKNOCKKNOCK;
    } else if (state == SENTKNOCKKNOCK) {
        if (theInput.equalsIgnoreCase("yes")) {
            //theOutput = clues[currentJoke];
            //theOutput = words[currentJoke];
            for(int i=0; i<secretWordLen; i++) theOutput = "-";
            state = SENTCLUE;
Onizuka
  • 431
  • 1
  • 4
  • 14
  • possible duplicate of http://stackoverflow.com/questions/7107297/what-is-the-easiest-way-to-generate-a-string-of-n-repeated-characters – holap Nov 18 '13 at 15:05

4 Answers4

3

Use StringBuilder:

StringBuilder builder = new StringBuilder();
for(int i=0; i<secretWordLen; i++) {
    builder.append('-');
}
theOutput = builder.toString();

This will do if all you want in theOutput is the series of dashes. If you want to have something before, just use builder.append() before appending the dashes.

The solution with += would work too (but needs theOutput to be initialized to something before, of course, so you don't append to null). Behind the scenes, Java will transform any += instruction into a code that uses StringBuilder. Using it directly makes it more clear what is happening, is more efficient in this case, and is in general a good thing to learn about how String are manipulated in Java.

Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58
1

You are overwriting your output-variable in each iteration.

Change it to:

theOutput += "-";
user1567896
  • 2,398
  • 2
  • 26
  • 43
0

instead of theOutput = "-"; use theOutput += "-";

sternze
  • 1,524
  • 2
  • 9
  • 15
0

You have to append the result each time.

for(int i=0; i<secretWordLen; i++)
 theOutput += "-"; 

When you write theOutput += "-"; that's the shorthand of

   theOutput = theOutput +"-";  
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307