-1

我正在尝试创建一个代码,该代码采用文本文件并将其按字母顺序排列。为此,我试图读取文件并将每个单词添加到数组中。我有一个想法如何去做,但不知道确切。这是我到目前为止所拥有的:

import java.io.*;
import java.util.Scanner;

public class assignment4 {
    public static void main(String[] args) throws IOException {

        if (args.length == 1){
            createArray(args[0]);
            System.exit(0);
        }

    }


    public static String createArray(String fileName) {
            File testFile = new File(fileName);
    Scanner inputFile = new Scanner(testFile);

    if (!testFile.exists()){
    System.out.println("File Doesn't Exist");
    System.exit(0);
    }

    String[] words;

    while(inputFile.hasNext()){
    for (int i=0;i<inputFile.length();i++){
    words[i] = inputFile.nextLine();
    }
    }

    return words[0];

    }
}

我知道大多数人可能是完全错误的,但我很困惑现在已经为此工作了 4 个小时......

4

2 回答 2

2
words[i] = inputFile.nextLine();

在这里,您尝试将输入文件中的下一行存储到数组的索引i中。words您还没有为 声明或赋值i,因此 Java 不会知道您要做什么。

对于标准数组,您必须为它们分配一个初始数组值,该值由明确数量的“槽”(索引)组成。使用 a Scanner,您可以通过读取所有行并丢弃值来计算行数。一旦你有了这个计数器,你就可以String[]用适当的大小来初始化。最后,您可以再次读取它们并将它们存储到数组中。

int counter = 0;

while (inputFile.hasNext()) {
    inputFile.nextLine();
    counter++;
}

inputFile = new Scanner(testFile); //to get to the beginning of the file

String[] words = new String[counter];

for (int i = 0; i < counter; i++) {
    words[i] = inputFile.nextLine();
}

这是非常糟糕的做法;仅仅为了找到它的长度而读取整个文件是一种矫枉过正的做法,而且是对资源的浪费。

因此,最好使用在您将元素放入其中时自动扩展的集合类型,例如ArrayList.

ArrayList<String> lines = new ArrayList<String>();

while (inputFile.hasNext()) {
    lines.add(inputFile.nextLine());
}

但很可能你的任务要求你同时使用Scanner和标准String[]String[]在这种情况下,您可以手动更改大小:

String[] words = new String[0];

while (inputFile.hasNext()) {
    words = Arrays.copyOf(words, words.length + 1);
    words[words.length - 1] = inputFile.nextLine();
}

或者

String[] words = new String[0];

while (inputFile.hasNext()) {
    String temp = new String[words.length + 1];
    System.arraycopy(words, 0, temp, 0, words.length);
    temp[temp.length - 1] = inputFile.nextLine();
    words = temp;
}
于 2013-10-13T01:06:25.170 回答
0

ArrayList words = new ArrayList(); while (inputFile.hasNextLine()){ String word = inputFile.getNextLine(); words.add(word); }

由于您不知道它有多大,因此您应该使用 arrayList。然后,您可以按字母顺序或任何您需要的顺序排序。

于 2013-10-13T01:04:10.383 回答