-2

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) + " "));
        }
    }
}
Amo Ra
  • 5
  • 3
  • 6
    Your question is unclear. What part are you having trouble with? Creating a random digit? – matt Sep 28 '20 at 13:02
  • Sort the numbers in an Array with Arrays.sort and reverse it. The highest number (positive) is then the first entry and the lowest number (most likeley negative) will be last. – funky Sep 28 '20 at 13:03
  • Welcome to StackOverflow! To post new questions you need to be clear describing the problem. You are mixing output and number generation: have you a problem with output random number or in generating them? Please update your question being more clear. Thanks – Mattia Merlini Sep 28 '20 at 13:09
  • 1
    1. [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java). 2. [The List Interface](https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html) 3. [Writing a list to a file](https://stackoverflow.com/questions/13597373/writing-a-list-to-a-file) – Abra Sep 28 '20 at 13:21
  • I need a list which is filled for a half only with random positive digits, and another half only with random negative – Amo Ra Sep 28 '20 at 13:50

2 Answers2

2

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.

Aleksey Kurkov
  • 228
  • 2
  • 12
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);

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

Niyas
  • 209
  • 1
  • 7