【问题标题】:How can I read only one thing in from a textfile?如何从文本文件中只读取一件事?
【发布时间】:2016-02-10 04:31:33
【问题描述】:

我可以从文件中读取,并且能够通过更改 for 循环中的数字来更改给定的行数,但我不希望我的文件中的所有数字都像这样并排显示。我需要它们都随机一个一个地下去。

public class Assignment2 {

    public static void main(String[] args) throws IOException 
    {
        // Read in the file into a list of strings
        BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
        List<String> lines = new ArrayList<String>();

        String line = reader.readLine();

        while( line != null ) {
            lines.add(line);
            line = reader.readLine();
        }

        // Choose a random one from the list
        Random r = new Random();

        for (int p = 0; p<3; p++)
        {
            String randomString = lines.get(r.nextInt(2));
            System.out.println(lines);
        }
    }
}

【问题讨论】:

  • 请解释清楚你的意思。
  • 输出是所有并排的数字,然后生成我分配的许多列。我需要让数字随机下降,直到有 20。我的 txt 文件是 20 'enter' 10 'enter' 15 等等

标签: java


【解决方案1】:

我想你要打印的是

String randomString = lines.get(r.nextInt(2));
System.out.println(randomString);

仅显示此列表中的前 20 个随机行,可能有 100 行

for (int i = 0; i < 20; i++) {

   int rowNum = r.nextInt(lines.size ());
   System.out.println(lines.get(rowNum);
}

【讨论】:

  • 现在我怎样才能让它只读取文本文件中的数字数量?抱歉,我对此有点陌生
  • LPT:学会更清楚地沟通。什么意思?
  • 我的 for 放错地方了吗?我试图只从 100 个列表中读取 20 个随机数
  • 谢谢我,很抱歉一开始没能理解我
  • 所以我又卡住了。我如何将它们放入输入文件中,而不是将 20 个数字打印出来?尝试了一些东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 2013-10-16
相关资源
最近更新 更多