1

Task: There are 2 files that each contain a series of ordered numbers, separated by space. Write a program that produces a third file that will contain the ascending sequence of numbers. When solving, you are not allowed to use any type of collection. File 1 : 1 18 40 100 File 2: 0 10 15 80 1001 I managed to convert the number to a String, but in the output file i got only the frist two numbers sorted: 0 1

    FileWriter outputFile;
    Scanner sc1 = null;
    Scanner sc2 = null;
    try {
       
        sc1 = new Scanner(new FileReader("Numbers1.txt"));
        sc2 = new Scanner(new FileReader("Numbers2.txt"));
        outputFile = new FileWriter("NumbersMerge.txt");
        int c = sc1.nextInt();
        int d = sc2.nextInt();
        while (sc1.hasNext() && sc2.hasNext()) {
            if (c < d) {
                outputFile.write(Integer.toString(c) + " ");
                sc1.nextLine();
            } else if (c > d) {
                outputFile.write(Integer.toString(d) + " ");
                sc2.nextLine();
            } else {
                outputFile.write(Integer.toString(c));
                outputFile.write(Integer.toString(d));
                sc1.nextLine();
                sc2.nextLine();
            }
        }
         if (sc1.hasNext()) {
            outputFile.write(Integer.toString(c));
            sc1.nextLine();
        }
        if (sc2.hasNext()) {
            outputFile.write(Integer.toString(d));
            sc2.nextLine();
        }
        outputFile.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (sc1 != null && sc2 != null) {
            sc1.close();
            sc2.close();
        }
    }

Thank you in advance!

bumbi007
  • 25
  • 5
  • 1
    You're using a `write` method passing an integer. [This](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/OutputStreamWriter.html#write(int)) is its documentation. Try and convert the number to a `String` first, so you'll use [this](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/Writer.html#write(java.lang.String)) method instead. – Federico klez Culloca May 01 '22 at 17:17
  • Thank you! I managed to convert the number to a String, but in the output file i've only got the first 2 numbers sorted. – bumbi007 May 01 '22 at 18:45

0 Answers0