【发布时间】:2016-02-18 07:46:24
【问题描述】:
writefile() 方法应该将给定数组中的所有整数写入给定的输出文件,每行一个。对于这部分,merge 方法应该返回一个足够大的新数组来保存前两个数组(a 和 b)的内容,然后将前两个复制到该数组中,不考虑顺序。
这是运行程序时在命令行中输入的内容:
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
【问题讨论】:
-
哪个部分不能编译?用什么信息?
-
它不喜欢行 output.prinln(merge(int[] a, int [] b);
-
因为你使用 new 关键字创建数组,如果你想传递一个已经存在的数组,你可以只使用它的名字 a 或 b。
标签: java arrays compiler-errors command-line-arguments printstream