Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 随机字生成器,我想限制它从.txt文件读取的字的大小,最多3个字符_Java - Fatal编程技术网

Java 随机字生成器,我想限制它从.txt文件读取的字的大小,最多3个字符

Java 随机字生成器,我想限制它从.txt文件读取的字的大小,最多3个字符,java,Java,//Random word generator,我想限制它从.txt文件读取的单词的大小//最多为3个字符,并且不使用//只返回System.Out.Print public void RandomWordGenerator() { List<String> words = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader("dictionar

//Random word generator,我想限制它从.txt文件读取的单词的大小//最多为3个字符,并且不使用//只返回System.Out.Print

public void RandomWordGenerator() {
    List<String> words = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader("dictionary.txt"))) {
        String word;
        while ((word = reader.readLine()) != null) {
            words.add(word);
        }
    } catch (IOException e) {
        System.out.println("Unable to find file");
    }
    Random random = new Random();
    String randomWord = words.get(random.nextInt(words.size()));
    System.out.println(randomWord);
public void RandomWordGenerator(){
List words=new ArrayList();
try(BufferedReader=newbufferedreader(newfilereader(“dictionary.txt”)){
字符串字;
while((word=reader.readLine())!=null){
添加(word);
}
}捕获(IOE异常){
System.out.println(“找不到文件”);
}
随机=新随机();
String randomWord=words.get(random.nextInt(words.size());
System.out.println(随机字);

您只需使用字符串的长度字段即可获得其长度

public void RandomWordGenerator() {
    List<String> words = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader("dictionary.txt"))) {
        String word;
        while ((word = reader.readLine()) != null) {
            words.add(word);
        }
    } catch (IOException e) {
        System.out.println("Unable to find file");
    }
    Random random = new Random();
    String randomWord = words.get(random.nextInt(words.size()));
    System.out.println(randomWord);
String word;
while ((word = reader.readLine()) != null) {
    if (word.trim().length <= MAX_LENGTH) {
       words.add(word);
    } 
}
字符串字;
while((word=reader.readLine())!=null){

如果(word.trim().length)是您面临的问题。请务必说明您得到了什么以及您期望得到什么。
List lines=Files.lines(Path.of(“myFile.txt”))).filter(line->line.length更喜欢使用
ThreadLocalRandom.current()
而不是
new Random()
,它速度更快,而且有更多的方法(
max
)我想他也愿意接受长度较短的单词,例如
1
2
。因此您可能希望将条件更改为
是,谢谢,我已更新了答案