开发者

Java - printing random word

I'm having problems with an exercise. I need to print five random words, between min and max letters.

This is what I've done:

package Vjezba;
import acm.program.*;
import acm.util.RandomGenerator;

import java.util.*;

public class String2 extends ConsoleProgram {
public void run () {
    for (int i = 0; i<5; i++){
        String a = randomWord();
        println(a);
    }

}

private String randomWord() {
    int a = rgen.nextInt(MIN_LETTER, MAX_LETTER);
    for (int x=0; x<a; 开发者_Python百科x++){
        String niz = "";
        char c = randomChar();
        niz += 'c';
    }
    return niz;

}



private char randomChar(){
    return (char) rgen.nextInt('a', 'z');
}

private static RandomGenerator rgen = new RandomGenerator();
private static int MIN_LETTER = 3;
private static int MAX_LETTER = 10;
    }

I have problems with returning String. Dunno how to do it.


You're declaring your String inside your for loop; every time it loops you get a new (empty) String. You're also adding the character 'c', not the contents of your char c

String niz = "";
for (int x=0; x<a; x++){
    //String niz = "";
    char c = randomChar();
    niz += c; // c not 'c'
}

And while in this trivial case it doesn't really matter, a String in java is immutable - it can't be changed. Every time you do niz += c it creates a new string. Any time you're building a string you want to use a StringBuilder:

StringBuilder niz = new StringBuilder();
for (int x=0; x<a; x++){
    char c = randomChar();
    niz.append(c);
}
return niz.toString();


Ignore my comment, I hadn't woken up yet. Your randomWord() has a scope issue; you're declaring your String variable inside of your for loop and then trying to return it after the loop ends - I imagine you're getting a compile error. Modify it so that the empty String declaration is before the for loop.


niz += 'c'; should be niz = niz + c; or niz += c; [personally I prefer the first, since it is more clear that the object is not modified but the reference is changed].

also, niz should be declared out of the loop's scope [before the for line].

String niz = "";
for (int x=0; x<a; x++){
    char c = randomChar();
    niz = niz + c;
}
return niz;

you might want to use StringBuilder if performance is an issue, but I don't think it is the case in here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜