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?

3
  • don't use System.out.println, but maybe the StringBuilder ? docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html Commented Jul 23, 2014 at 18:18
  • What's wrong with creating a String/StringBuilder outside the loop and appending the generated characters to it inside the loop? Commented Jul 23, 2014 at 18:18
  • You got an answer but you don't show any effort trying to do it yourself. Pity. Commented Jul 23, 2014 at 18:28

1 Answer 1

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.

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

5 Comments

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
@McAdam331 nope. please don't do that :) evil.
Why is that evil? I've always used that approach.
@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.
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 the compiler can't optimize to a Stringbuilder inside of a loop, but typically will otherwise. Thanks for the insight!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.