このwritefile()
メソッドは、指定された出力ファイルに、指定された配列内のすべての整数を 1 行に 1 つずつ書き出す必要があります。この部分では、merge メソッドは、最初の 2 つの配列 (a と b) の内容を保持するのに十分な大きさの新しい配列を返し、最初の 2 つを順序に関係なくその配列にコピーする必要があります。
これは、プログラムを実行するときにコマンドラインに入力されるものです。
java Merge1 sorted1.txt sorted2.txt sortedout.txt
これが sorted1.txt の内容です。
12 51 80 138 212 237 306 316 317 337 356 413 422 511 534 577 621 708 717 738 738 846 850 900
これが sorted2.txt です。
33 41 77 101 157 164 192 235 412 415 484 499 500 533 565 630 667 786 846 851 911 949 968 986
どうすればいいですか?
これまでの私のコードは次のとおりです。
import java.io.*;
import java.util.Scanner;
public class Merge1
{
public static void main(String[] args)
{
File sorted1 = new File (args[0]);
File sorted2 = new File (args[1]);
File sortedout = new File (args[2]);
try{
Scanner input = new Scanner(sorted1);
readfile(input);
}
catch (FileNotFoundException e) {
System.out.println("File not found");
}
try{
Scanner input = new Scanner(sorted2);
readfile(input);
}
catch (FileNotFoundException e) {
System.out.println("File not found");
}
try{
Scanner input = new Scanner(sortedout);
readfile(input);
}
catch (FileNotFoundException e) {
System.out.println("File not found");
}
} // end main
static int[] readfile(Scanner input)
{
String num = "";
while(input.hasNextInt())
{
num += input.nextInt() + " ";
}
String[] array = num.split(" ");
int[] list = new int[array.length];
for(int i = 0; i < array.length; i++)
{
list[i] = Integer.parseInt(array[i]);
System.out.println(list[i]);
}
return list;
} // end readfile
static void writefile(PrintStream output, int[] a)
{
output.println(merge(int[] a, int[]b));
} // end writefile
static int[] merge(int[] a, int[] b)
{
int[] answer = new int[a.length + b.length];
int i = 0;
int j = 0;
int k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
{
answer[k] = a[i];
k++;
i++;
}
else
{
answer[k] = b[j];
k++;
j++;
}
}
while (i < a.length)
{
answer[k] = a[i];
k++;
i++;
}
while (j < b.length)
{
answer[k] = b[j];
k++;
j++;
}
return answer;
} // end merge
} // end Merge1