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; 
1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, yup the += solution will append null as you mentioned if not initialized.
1

You are overwriting your output-variable in each iteration.

Change it to:

theOutput += "-"; 

Comments

0

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

Comments

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 +"-"; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.