【问题标题】:Storing an array of strings without initializing the size存储字符串数组而不初始化大小
【发布时间】:2016-10-29 19:40:48
【问题描述】:

背景:这个程序读入一个文本文件并用用户输入替换文件中的一个词。

问题:我正在尝试从文本文件中读取一行文本并将这些单词存储到一个数组中。

现在数组大小是硬编码的,带有许多索引用于测试目的,但我想让数组能够读取任何大小的文本文件。

这是我的代码。

public class FTR {

public static Scanner input = new Scanner(System.in);
public static Scanner input2 = new Scanner(System.in);
public static String fileName = "C:\\Users\\...";
public static String userInput, userInput2;
public static StringTokenizer line;
public static String array_of_words[] = new String[19]; //hard-coded

/* main */
public static void main(String[] args) {
    readFile(fileName);
    wordSearch(fileName);
    replace(fileName);

}//main

/*
 * method: readFile
 */
public static void readFile(String fileName) {
    try {
        FileReader file = new FileReader(fileName);
        BufferedReader read = new BufferedReader(file);

        String line_of_text = read.readLine();
        while (line_of_text != null) {
            System.out.println(line_of_text);
            line_of_text = read.readLine();
        }
    } catch (Exception e) {
        System.out.println("Unable to read file: " + fileName);
        System.exit(0);
    }
    System.out.println("**************************************************");
}

/*
* method: wordSearch
*/
public static void wordSearch(String fileName) {
    int amount = 0;
    System.out.println("What word do you want to find?");
    userInput = input.nextLine();
    try {
        FileReader file = new FileReader(fileName);
        BufferedReader read = new BufferedReader(file);

        String line_of_text = read.readLine();
        while (line_of_text != null) { //there is a line to read
            System.out.println(line_of_text);
            line = new StringTokenizer(line_of_text); //tokenize the line into words
            while (line.hasMoreTokens()) { //check if line has more words
                String word = line.nextToken(); //get the word 
                if (userInput.equalsIgnoreCase(word)) {
                    amount += 1; //count the word
                }
            }
            line_of_text = read.readLine(); //read the next line
        }
    } catch (Exception e) {
        System.out.println("Unable to read file: " + fileName);
        System.exit(0);
    }
    if (amount == 0) { //if userInput was not found in the file
        System.out.println("'" + userInput + "'" + " was not found.");
        System.exit(0);
    }
    System.out.println("Search for word: " + userInput);
    System.out.println("Found: " + amount);
}//wordSearch

/*
* method: replace
*/
public static void replace(String fileName) {
    int amount = 0;
    int i = 0;
    System.out.println("What word do you want to replace?");
    userInput2 = input2.nextLine();
    System.out.println("Replace all " + "'" + userInput2 + "'" + " with " + "'" + userInput + "'");
    try {
        FileReader file = new FileReader(fileName);
        BufferedReader read = new BufferedReader(file);

        String line_of_text = read.readLine();
        while (line_of_text != null) { //there is a line to read
            line = new StringTokenizer(line_of_text); //tokenize the line into words
            while (line.hasMoreTokens()) { //check if line has more words
                String word = line.nextToken(); //get the word 
                if (userInput2.equalsIgnoreCase(word)) {
                    amount += 1; //count the word
                    word = userInput;
                }
                array_of_words[i] = word; //add word to index in array   
                System.out.println("WORD: " + word + " was stored in array[" + i + "]");
                i++; //increment array index     
            }
  //THIS IS WHERE THE PRINTING HAPPENS
            System.out.println("ARRAY ELEMENTS: " + Arrays.toString(array_of_words));
            line_of_text = read.readLine(); //read the next line
        }
        BufferedWriter outputWriter = null;
        outputWriter = new BufferedWriter(new FileWriter("C:\\Users\\..."));
        for (i = 0; i < array_of_words.length; i++) { //go through the array
            outputWriter.write(array_of_words[i] + " "); //write word from array to file
        }
        outputWriter.flush();
        outputWriter.close();
    } catch (Exception e) {
        System.out.println("Unable to read file: " + fileName);
        System.exit(0);
    }
    if (amount == 0) { //if userInput was not found in the file
        System.out.println("'" + userInput2 + "'" + " was not found.");
        System.exit(0);
    }
}//replace
}//FTR

【问题讨论】:

  • 使用ArrayList?你也没有写一个实际的问题(只是一个意图或愿望的陈述)

标签: java arrays string file stringtokenizer


【解决方案1】:

您可以使用java.util.ArrayList(与固定大小的数组不同的是动态增长)通过将数组替换为以下代码来存储字符串对象(测试文件行):

public static List<String> array_of_words = new java.util.ArrayList<>();

您需要使用add(string) 添加一行(字符串)和get(index) 检索该行(字符串)

请参考以下链接了解更多详情: http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

【讨论】:

  • 非常感谢!我会更多地研究使用 ArrayList。
【解决方案2】:

您不妨试试ArrayList

在 Java 中,普通数组不能在没有给出初始大小的情况下进行初始化,并且它们不能在运行时扩展。而 ArrayLists 具有 List 接口的 resizable-array 实现。ArrayList 还带有许多有用的内置函数,例如

尺寸()

isEmpty()

包含()

克隆()

和其他人。除此之外,您始终可以使用 ArrayList 函数 toArray() 将 ArrayList 转换为简单数组。希望这能回答你的问题。我会准备一些代码和大家分享,进一步解释使用List接口可以实现的东西。

【讨论】:

  • 非常感谢!我将更多地研究使用 ArrayList 而不是普通数组。
【解决方案3】:

不使用原生 [] 数组,而是使用任何类型的 java 集合

List<String> fileContent = Files.readAllLines(Paths.get(fileName));
fileContent.stream().forEach(System.out::println);

long amount = fileContent.stream()
    .flatMap(line -> Arrays.stream(line.split(" +")))
    .filter(word -> word.equalsIgnoreCase(userInput))
    .count();

List<String> words = fileContent.stream()
    .flatMap(line -> Arrays.stream(line.split(" +")))
    .filter(word -> word.length() > 0)
    .map(word -> word.equalsIgnoreCase(userInput) ? userInput2 : word)
    .collect(Collectors.toList());

Files.write(Paths.get(fileName), String.join(" ", words).getBytes());

当然,您可以更传统地使用此类列表,使用循环

for(String line: fileContent) {
    ...
}

甚至

for (int i = 0; i < fileContent.size(); ++i) {
    String line = fileContent.get(i);
    ...
}

我只是喜欢流:)

【讨论】:

  • 非常感谢!谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
  • 2018-03-04
  • 2021-03-13
  • 1970-01-01
  • 2017-09-12
相关资源
最近更新 更多