英文:
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 <= 100; i++) {
wr.write(String.valueOf((i) + " "));
}
for (int a = -1; a >= -100; a--) {
wr.write(String.valueOf((a) + " "));
}
}
}
答案1
得分: 2
尝试使用 ArrayList
集合。
-
首先用值填充 ArrayList。
-
然后对该集合进行排序,例如使用工具方法
Collections.sort()
。 -
最后,开始创建文件。编写保存已排序集合逐个值的方法。
英文:
Try to work with ArrayList
collection.
-
First fill the ArrayList with values.
-
Then sort this collection, for example with util method
Collections.sort()
. -
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<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);
Generates 10 random numbers, reverses, collects to list and then writes to a file.
However, this doesnot handle duplicate random numbers.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论