对不起,如果我的标题令人困惑。我有一个与 Java 相关的作业。该任务的目标是创建一个程序,该程序将读取省和市的输入文件并将数据存储到二维数组中,一个用于省,一个用于城市(无重复)。之后,它将按字母顺序输出。如果这令人困惑,这里是它应该是什么样子的示例。
示例输入文件
Hamilton, Ontario
Montreal, Quebec
Vancouver, British Columbia
Sarnia, Ontario
Sherbrooke, Quebec
Winnipeg, Manitoba
Red Deer, Alberta
Edmonton, Alberta
Niagara Falls, Ontario
Port Elgin, Ontario
Victoria, British Columbia
Truro, Nova Scotia
Regina, Saskatchewan
Kingston, Ontario
Fredricton, New Brunswick
Grand Prarie, Alberta
Calgary, Alberta
Collingwood, Ontario
示例输出文件
British Columbia: Vancouver, Victoria
Alberta: Calgary, Edmonton, Grand Prarie, Red Deer
Saskatchewan: Regina
Manitoba: Winnipeg
Ontario: Collingwood, Hamilton, Kingston, Niagara Falls, Port Elgin, Sarnia
Quebec: Montreal, Sherbrooke
New Brunswick: Fredricton
Nova Scotia: Truro
这是我的主要课程
导入 java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.err.println("Usage: java -jar lab5.jar infile outfile");
System.exit(99);
}
Munge dataSorter = new Munge(args[0], args[1]);
dataSorter.openFiles();
dataSorter.readRecords();
dataSorter.writeRecords();
dataSorter.closeFiles();
}
}
到目前为止,这是我的 Munge 课程。
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Formatter;
import java.util.Scanner;
public class Munge {
private String inputFileName, outputFileName;
private Scanner inputFile;
private Formatter outputFile;
private int line = 0;
private String[] data;
public Munge(String inFileName, String outFileName) {
this.inputFileName = inFileName;
this.outputFileName = outFileName;
data = new String[100];
}
public void openFiles() throws FileNotFoundException {
File newFile = new File(inputFileName);
}
public void readRecords() {
while (inputFile.hasNext()) {
data[line] = inputFile.nextLine();
System.out.println(data[line]);
line++;
}
}
public void writeRecords() {
for (int i = 0; i < line; i++) {
String done[] = data[i].split(", ");
Arrays.sort(done);
for (int j = 0; j < done.length; j++) {
outputFile.format("%s\r\n", done[j]);
}
}
}
public void closeFiles() {
if (inputFile != null) {
inputFile.close();
}
if (outputFile != null) {
outputFile.close();
}
}
}
我的问题主要发生在我尝试运行程序时。我不断收到仅在 args.length < 2 时才会出现的消息。为什么会这样以及如何解决这个问题?我是否将 args[0] 和 args[1] 设置为相同的文件?