Skip to content
Advertisement

Print array without brackets and commas

I’m porting a Hangman game to Android and have met a few problems. The original Java program used the console, so now I have to somehow beautify the output so that it fits my Android layout.

How do I print an array without the brackets and commas? The array contains slashes and gets replaced one-by-one when the correct letter is guessed.

I am using the usual .toString() function of the ArrayList class and my output is formatted like: [ a, n, d, r, o, i, d ]. I want it to simply print out the array as a single String.

I fill the array using this bit of code:

List<String> publicArray = new ArrayList<>();

for (int i = 0; i < secretWordLength; i++) {
    hiddenArray.add(secretWord.substring(i, i + 1));
    publicArray.add("-");
}

And I print it like this:

TextView currentWordView = (TextView) findViewById(R.id.CurrentWord);
currentWordView.setText(publicArray.toString());

Advertisement

Answer

Basically, don’t use ArrayList.toString() – build the string up for yourself. For example:

StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
    builder.append(value);
}
String text = builder.toString();

(Personally I wouldn’t call the variable publicArray when it’s not actually an array, by the way.)

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement