Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Sort Two Text Files Alphabetically into one Text File
    text
    copied!<p>I need to take two text files and sort them alphabetically into one new created text file.</p> <p><strong>greekWriters.txt contains:</strong></p> <p>Aesop</p> <p>Euripides</p> <p>Homer</p> <p>Plato</p> <p>Socrates</p> <p><strong>romanWriters.txt contains:</strong></p> <p>Cicero</p> <p>Livy</p> <p>Ovid</p> <p>Virgil</p> <p><strong>This is my code:</strong> </p> <pre><code>import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Driver { public static void merge(String name1, String name2, String name3) { File file1 = null, file2 = null, file3 = null; Scanner input1 = null, input2 = null; PrintWriter output = null; try { file1 = new File(name1); file2 = new File(name2); file3 = new File(name3); input1 = new Scanner(file1); input2 = new Scanner(file2); output = new PrintWriter(file3); String s1 = input1.nextLine(); String s2 = input2.nextLine(); // Problem Area while (input1.hasNext() &amp;&amp; input2.hasNext()) { if(s1.compareToIgnoreCase(s2) &lt;= 0) { output.println(s1); s1 = input1.nextLine(); } else { output.println(s2); s2 = input2.nextLine(); } } if (s1.compareToIgnoreCase(s2) &lt;= 0) { output.println(s1 + "\n" + s2); } else { output.println(s2 + "\n" + s1); } while (input1.hasNext()) { output.println(input1.nextLine()); } while (input2.hasNext()) { output.println(input2.nextLine()); } } // problem area end catch (IOException e) { System.out.println("Error in merge()\n" + e.getMessage()); } finally { if (input1 != null) { input1.close(); } if (input2 != null) { input2.close(); } if (output != null) { output.close(); } System.out.println("Finally block completed."); } } public static void main (String[] args) { Scanner input = new Scanner(System.in); String name1, name2, name3; name1 = "greekWriters.txt"; name2 = "romanWriters.txt"; System.out.print("Output File: "); name3 = input.next(); merge(name1,name2,name3); } } </code></pre> <p><strong>This is the output:</strong></p> <p>Aesop</p> <p>Cicero</p> <p>Euripides</p> <p>Homer</p> <p>Livy</p> <p>Ovid</p> <p>Plato</p> <p>Virgil</p> <p>Socrates</p> <p>As you can see it is not in order (Virgil and Socrates), I believe the issue is by the while loop when the loop is reading the end of the text files in the compareToIgnoreCase methods. Please help me find the reason why it is not sorting correctly, I would like to sleep tonight. Thank you guys for your help in advance!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload