【发布时间】:2018-12-06 19:17:21
【问题描述】:
我有两个数据文件Test1和Test2。
Test1 数据:
1.0 2.0 3.0
2.0 4.0 5.0
3.0 1.0 2.0
4.0 9.0 2.0
7.0 0.0 0.0
8.0 7.0 1.0
10.0 2.0 5.0
11.0 0.0 0.0
13.0 1.0 1.0
15.0 1.0 1.0
17.0 2.0 2.0
Test2.txt
5.0 2.0 5.0 6.0
6.0 1.0 2.0 9.0
9.0 0.0 1.0 3.0
12.0 0.0 0.0 0.0
14.0 1.0 1.0 1.0
test4.txt(输出文件)
1.0 2.0 3.0
2.0 4.0 5.0
3.0 1.0 2.0
4.0 9.0 2.0
5.0 2.0 5.0 6.0
6.0 1.0 2.0 9.0
7.0 0.0 0.0
8.0 7.0 1.0
9.0 0.0 1.0 3.0
10.0 2.0 5.0
11.0 0.0 0.0
12.0 0.0 0.0 0.0
13.0 1.0 1.0
14.0 1.0 1.0 1.0
15.0 1.0 1.0
17.0 2.0 2.0
我的代码:
public class Insertelementfile {
public static void main(String args[])throws IOException{
Scanner X=new Scanner(new File("c:\\test1.txt"));
Scanner Y=new Scanner(new File("C:\\test2.txt"));
PrintWriter write1=null;
write1= new PrintWriter(new File("C:\\test4.txt"));
double a=0.0,d=0.0;
int i=0,j=0,k=0;
List<Double> list1=new ArrayList<>();
List<Double>list2=new ArrayList<>();
double[]arrX=new double[11];
double[]arrY=new double[5];
double[] s = new double[16];
while(X.hasNext()){
a = X.nextDouble();
list1.add(a);
double b=X.nextDouble();
double c=X.nextDouble();
}
while(Y.hasNext()) {
d = Y.nextDouble();
list2.add(d);
double e=Y.nextDouble();
double f=Y.nextDouble();
double g=Y.nextDouble();
}
for(int i1=0;i1<list1.size();i1++) {
arrX[i1]=list1.get(i1);
}
for(int j1=0;j1<list2.size();j1++){
arrY[j1]=list2.get(j1);
}
while(i<arrX.length && j<arrY.length){
if (arrX[i] < arrY[j]){
s[k]=arrX[i];
i++;
}
else{
s[k] = arrY[j];
j++;
}
k++;
}
// Copy the remaining elements in arrX to s
if (i < arrX.length) {
// arraycopy(source, sourcepos, dest, destpos, numOfElements)
System.arraycopy(arrX, i, s, k, (arrX.length - i));
}
// Copy the remaining elements in arrY to s
if (j < arrY.length) {
// arraycopy(source, sourcepos, dest, destpos, numOfElements)
System.arraycopy(arrY, j, s, k, (arrY.length - j));
}
System.out.println( Arrays.toString(s));
write1.write(Arrays.toString(s));
write1.flush();
write1.close();
}
}
我得到的输出是这样的: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 17.0] 但是我的输出中没有剩余的列。我将两个文件的第一列作为我的关键属性并根据那里的顺序插入元素。我应该怎么做才能得到我想要的输出?
【问题讨论】:
-
在您的第一个 for 循环中,您正在读取一行的第二个和第三个值,但您没有将它们存储在任何地方,它们根本没有被使用。此外,我强烈建议您更好地命名变量。例如,使用“test1SecondValue”代替“b”可以更容易理解发生了什么。
-
另外,您可以简单地调用 arraylist.toArray(
),而不是手动将 ArrayList 转换为带有循环的数组。 -
我怎样才能得到我想要的输出?我得到的输出是整个输出的一部分。