user2993456
user2993456

Reputation:

create a single String variable out of multiple random character variables

I want to generate a fixed amount of random random characters, and then save those characters to a String variable. Here is the simple 'for' loop I have written so far:

String listChars = "";

for(int i = 0; i < 50; i++){
    char randomChar = (char)((Math.random()*255)+32);
    System.out.print(randomChar);
    String listChars = "" + randomChar;
}

System.out.print(listChars);

I excluded the first 32 characters to avoid the control characters. My for loop prints 50 random characters to the screen just fine, but my listChars variable doesn't seem to be storing the values the way I want. (I want to store them as one 50 character long string)

Is there a way to make this work, perhaps with an array?

Upvotes: 0

Views: 204

Answers (6)

JDGuide
JDGuide

Reputation: 6525

You do not need to declare new String variable listwords inside the loop .

Remove :-

String listwords = "" + randomChar;

Add :-

listwords = "" + randomChar;

Upvotes: 0

Arjit
Arjit

Reputation: 3456

Try to use StringBuilder or StringBuffer instead of String variable. They consumes less memory.

StringBuilder is better than StringBuffer in terms of memory but it is not thread safe.

StringBuffer sb = new StringBuffer("");

Try to use like this in your for loop

sb.append(randomChar);

Upvotes: 1

York Xtrem
York Xtrem

Reputation: 58

String listwords = "";
    for(int i = 0; i < 50; i++){
    char randomChar = (char)((Math.random()*255)+32);
    System.out.print(randomChar);
    listwords = listwords + randomChar;
    }
    System.out.print(listwords);

Upvotes: 0

pezetem
pezetem

Reputation: 2541

try this:

String listwords = "";
        for(int i = 0; i < 50; i++){
        char randomChar = (char)((Math.random()*255)+32);
        System.out.print(randomChar);
        listwords += randomChar;
        }
        System.out.print(listwords);

Upvotes: 0

Harmlezz
Harmlezz

Reputation: 8068

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < 50; i++) {
        char randomChar = (char)((Math.random()*255)+32);
        System.out.print(randomChar);
        builder.append(randomChar);
    }
    System.out.print(builder);        

Upvotes: 2

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

You have defined a duplicated variable in the for loop.

This:

String listwords = "" + randomChar;

should be:

listwords += randomChar;

Upvotes: 4

Related Questions