列表中正数在开头,负数在结尾。

huangapple go评论69阅读模式
英文:

List with positive numbers at the beginning and negative at the end

问题

我只是刚刚开始,但找不到我的问题的答案。对于任何想法,我会非常感激。

我需要一个列表,列表的一半只填充随机的正数,另一半只填充随机的负数。这个列表应该被添加到一个文件中。

我不明白怎么做。有任何想法吗?

目前我只能像这样在文件中写入字符串:

try (BufferedWriter wr = new BufferedWriter(new FileWriter(numbers));
     BufferedReader rd = new BufferedReader(new FileReader(numbers)) {
    if (numbers.exists()) {
        for (int i = 0; i <= 100; i++) {
            wr.write(String.valueOf((i) + " "));
        }
        for (int a = -1; a >= -100; a--) {
            wr.write(String.valueOf((a) + " "));
        }
    }
}
英文:

I'm just at the beginning but cannot find answer for my question. For any ideas will be very grateful.

I need a list which is filled for a half only with random positive digits, and another half only with random negative. The list should be added to a file

I do not understand how to do that. Any ideas?

For now I only can write String in a file like:

try (BufferedWriter wr = new BufferedWriter(new FileWriter(numbers));
     BufferedReader rd = new BufferedReader(new FileReader(numbers)) {
    if (numbers.exists()) {
        for (int i = 0; i &lt;= 100; i++) {
            wr.write(String.valueOf((i) + &quot; &quot;));
        }
        for (int a = -1; a &gt;= -100; a--) {
            wr.write(String.valueOf((a) + &quot; &quot;));
        }
    }
}

答案1

得分: 2

尝试使用 ArrayList 集合。

  1. 首先用值填充 ArrayList。

  2. 然后对该集合进行排序,例如使用工具方法 Collections.sort()

  3. 最后,开始创建文件。编写保存已排序集合逐个值的方法。

英文:

Try to work with ArrayList collection.

  1. First fill the ArrayList with values.

  2. Then sort this collection, for example with util method Collections.sort().

  3. Finally, work on creating file. Write method for saving sorted collection value by value.

答案2

得分: 0

List<String> numbers = IntStream.range(0, 10)
    .map(x -> random.nextInt(100) * (random.nextBoolean() ? -1 : 1))
    .boxed()
    .sorted(Collections.reverseOrder())
    .map(String::valueOf)
    .collect(Collectors.toList());
Files.write(Paths.get("D://test.txt"), numbers);

生成10个随机数,逆序排列,收集到列表中,然后写入文件。
然而,这段代码没有处理重复的随机数。

英文:
List&lt;String&gt; numbers = IntStream.range(0, 10).map(x -&gt; random.nextInt(100) * (random.nextBoolean() ? -1 : 1)).boxed()
				.sorted(Collections.reverseOrder()).map(String::valueOf).collect(Collectors.toList());
Files.write(Paths.get(&quot;D://test.txt&quot;), numbers);

Generates 10 random numbers, reverses, collects to list and then writes to a file.
However, this doesnot handle duplicate random numbers.

huangapple
  • 本文由 发表于 2020年9月28日 20:58:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64102675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定