【问题标题】:I got the code to print a random value from a column in csv except it works sometimes, and sometimes it does not我得到了从 csv 中的列打印随机值的代码,但有时它可以工作,有时它不能
【发布时间】:2021-03-14 20:44:57
【问题描述】:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;

public class FileVersion2_Class {
    public static void main(String[] args) throws Exception {
        String line = "";
        String splitBy = ",";
        int counter = 0;
        try {
            BufferedReader br = new BufferedReader(
                    new FileReader("C:\\Users\\myfile.csv"));
            while ((line = br.readLine()) != null) {
                counter++;
                int min = 0;
                int max = 151;
                int random_int = (int) (Math.random() * (max - min + 1) + min);
                if (counter == random_int) {
                    String[] file = line.split(splitBy);
                    System.out.println(file[0]);
                }
            }
        } catch (

        IOException e) {
            e.printStackTrace();
        }
    }
}

我按下运行,有时它会从列中打印出一个值,有时会出现空白行,有时会从同一列中打印出 3 个不同的值。有人可以解释为什么会这样吗?我的 Math.random 方法有缺陷吗?

【问题讨论】:

  • 问题是你得到一个随机数。然后检查它是否与您拥有的counter 相等。当然,有时它会打印一个值或多个值或不打印。如果我理解你的问题是什么。检查你的逻辑和你想要实现的目标。祝你好运
  • 您的文件中有多少列?您知道其中包含 "A,B,C" 的列看起来像 3 列而不是 1 列...您的 CSV 中真的有 151 列吗??
  • 哦,计数器用于倒计时的行,file[0] 是列的位置。我意识到如果我使用 if counter == # 它将从该行打印,但我试图使其成为随机行。大声笑

标签: java csv bufferedreader


【解决方案1】:

这里的问题是您正在为文件中的每一行重新生成随机整数。因此,不能保证counter == random_int 永远为真,或只为真一次。

您应该做的是在 while 循环之前生成随机数。

【讨论】:

    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    相关资源
    最近更新 更多