1

I'm trying to make a variable out of the result of a for loop. First of all is this possible? If it is possible how do i do it? This is my code so far:

Random r = new Random();
Random n = new Random();

int p = (int)(n.nextInt(14));

for (int i = 0; i < p; i++) {
  char c = (char) (r.nextInt(26) + 'a');
  System.out.println(c);}

  String word = ("output of forloop goes here");

I want to put all the randomly generated letters into one word using the for loop. How do I do this?

brandon Whe
  • 206
  • 1
  • 14
  • don't use `System.out.println`, but maybe the `StringBuilder` ? http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html – dognose Jul 23 '14 at 18:18
  • What's wrong with creating a String/StringBuilder outside the loop and appending the generated characters to it inside the loop? – Timo Geusch Jul 23 '14 at 18:18
  • You got an answer but you don't show any effort trying to do it yourself. Pity. – Jonathan Drapeau Jul 23 '14 at 18:28

1 Answers1

5

Use StringBuilder :

StringBuilder sb = new StringBuilder();
for (int i = 0; i < p; i++) {
  char c = (char) (r.nextInt(26) + 'a');
  sb.append(c);
}

Then you can call sb.toString() to get the resulting String.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • This will work, but you don't necessarily need to use StringBuilder. You could declare a string before the loop: `String output = ""` and then instead of writing `sb.append(c)` you could write `output += c` – AdamMc331 Jul 23 '14 at 18:22
  • 1
    @McAdam331 nope. please don't do that :) evil. – Suresh Atta Jul 23 '14 at 18:24
  • Why is that evil? I've always used that approach. – AdamMc331 Jul 23 '14 at 18:24
  • 1
    @McAdam331 That would cause a construction of a new String object in each iteration, since String is immutable. Though the compiler might optimize it into a StringBuilder. – Eran Jul 23 '14 at 18:25
  • Oh, I never realized that's what was happening. Actually, @Eran, after you mentioned that I did a little search and according to [this post](http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java) the compiler can't optimize to a Stringbuilder inside of a loop, but typically will otherwise. Thanks for the insight! – AdamMc331 Jul 23 '14 at 18:27