2 つのテキスト ファイルを取得し、それらをアルファベット順に並べ替えて、新しく作成した 1 つのテキスト ファイルにする必要があります。
greekWriters.txt には以下が含まれます。
イソップ
エウリピデス
ホーマー
プラトン
ソクラテス
romanWriters.txt には以下が含まれます。
シセロ
リヴィ
オビッド
バージル
これは私のコードです:
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() && input2.hasNext())
{
if(s1.compareToIgnoreCase(s2) <= 0)
{
output.println(s1);
s1 = input1.nextLine();
}
else
{
output.println(s2);
s2 = input2.nextLine();
}
}
if (s1.compareToIgnoreCase(s2) <= 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);
}
}
これは出力です:
イソップ
シセロ
エウリピデス
ホーマー
リヴィ
オビッド
プラトン
バージル
ソクラテス
順序どおりではないことがわかるように (Virgil と Socrates)、ループが compareToIgnoreCase メソッドでテキスト ファイルの末尾を読み取っているときに、while ループが原因であると考えられます。正しくソートされない理由を見つけてください。今夜は寝たいです。事前に助けてくれてありがとう!