[英]How to Merge N sort two text files
我必須閱讀兩個看起來像這樣的文本文件。
FileOne:10 1 2 3 4 5 67 75 47 18
FileTwo:5 65 74 57 68 28 38
第一個數字表示我應使用多少個整數來填充數組。
我需要讀取文件的第一行,然后使用該數字用指定的許多元素填充兩個數組。
我已經弄清楚了如何讀取兩個文本文件並將它們連接在一起,但是我無法弄清楚如何僅從文件中獲取第一個數字並用它來確定之后應該使用多少個數字。
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class ReadData {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter the first file name: ");
String input = s.nextLine();
System.out.println("Please enter the second file name: ");
String input2 = s.nextLine();
int[] data = readFiles(input);
int[] data2 = readFiles(input2);
//System.out.println(Arrays.toString(data));
//System.out.println(Arrays.toString(data2));
System.out.println(Arrays.toString(concat(data, data2)));
}
public static int[] readFiles(String file) {
try {
File f = new File(file);
Scanner s = new Scanner(f);
int counter = 0;
while(s.hasNextInt()) {
counter++;
s.nextInt();
}
int[] arr = new int[counter];
Scanner s1 = new Scanner(f);
for(int i = 0; i < arr.length; i++)
arr[i] = s1.nextInt();
return arr;
}
catch(Exception e) {
return null;
}
}
static int[] concat(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}
int[] result = new int[length];
int pos = 0;
for (int[] array : arrays) {
for (int element : array) {
result[pos] = element;
pos++;
}
}
return result;
}
}
對於初學者,我建議將整個行作為單個字符串讀取,然后使用解析器解析它,它將使用空格作為定界符。 您將獲得一個包含所有數字的DS,這是一種更為優雅的解決方案。 (Java解析簡單解決方案: http : //pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html )
一旦您擁有包含數字的DS,便可以在上面愉快地進行迭代,記住第一個值確定了DS上將來的迭代次數。
假設您使用的是Java 8,我建議您使用流功能來這樣做: http : //winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
如果需要任何詳細說明和好運,請發表評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.