简体   繁体   English

Java - 打印随机字

[英]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; 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. 我有返回String的问题。 Dunno how to do it. 不知道怎么做。

You're declaring your String inside your for loop; 你在for循环中声明了你的String ; every time it loops you get a new (empty) String. 每次循环都会得到一个新的(空)字符串。 You're also adding the character 'c', not the contents of your char c 你还要添加字符'c',而不是你的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. 虽然在这个简单的情况下它并不重要,但java中的String是不可变的 - 它无法更改。 Every time you do niz += c it creates a new string. 每次你执行niz += c它会创建一个新字符串。 Any time you're building a string you want to use a StringBuilder : 无论何时构建字符串,都要使用StringBuilder

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

niz += 'c'; should be niz = niz + c; 应该是niz = niz + c; or niz += c; 或者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]. 另外, niz应该在循环范围之外[在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. 如果性能是一个问题,你可能想使用StringBuilder ,但我认为不是这里的情况。

Ignore my comment, I hadn't woken up yet. 忽略我的评论,我还没有醒过来。 Your randomWord() has a scope issue; 你的randomWord()有一个范围问题; 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. 你在for循环中声明了你的String变量,然后在循环结束后尝试返回它 - 我想你得到了一个编译错误。 Modify it so that the empty String declaration is before the for loop. 修改它,使空字符串声明在for循环之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM