【问题标题】:How do I read a populated array from a .txt file?如何从 .t​​xt 文件中读取填充数组?
【发布时间】:2014-12-18 23:25:13
【问题描述】:

我有一个 .txt 文件,其中包含 87 个四个字母的单词。我本质上是在制作一个刽子手游戏,其中用户开始游戏,并在 0 到 86 之间生成一个随机数,然后程序转到 .txt 文件并挑选出该单词供用户猜测。这是我第一次尝试这样做,因为我是一名新的编程学生,而我正在使用的书几乎没有任何帮助。所以...这是我一直在做的:

class ReturnRandomInteger {

    public int randomInteger() {
        int randomInt = 0;
        for (int i = 0; i < 1; i++) {
        randomInt = (int) (Math.random() * 86) + 0;
    }
return randomInt;
}
    public static String getWord(int randomInt, String line) {
        FourLetterWords newObject = new FourLetterWords();
        if (randomInt == String line)

    }
}

class FourLetterWords {

    public static void readFile() {

    try {
        String fileName = "C//FourLetterWords.txt";
        File fourLetterWords = new File(fileName);
        Scanner in = new Scanner(fourLetterWords);

        ArrayList<FourLetterWords> words = new ArrayList<>();

        while (in.hasNextLine()) {
            String line = in.nextLine();
        }

    } catch (FileNotFoundException ex) {
    System.out.println("File not found.");
    }
}
}

首先,我不知道我的 try and catch 是否正确。该文件的名称是 FourLetterWords.txt。如果它是错误的,我想知道读取 .txt 文件中每一行的正确方法是什么。现在在我的 ReturnRandomInteger 类中,我从 FourLetterWords 类中创建了新对象,您可以看到我想要做的是拥有它,这样如果用户生成的随机整数等于 .txt 文件中的相应行,那么它将在该行中返回该单词。显然, int 不能等于 String 那么我应该如何对应我拥有的 .txt 文件中的单词生成的整数?

如果能得到任何帮助,我将不胜感激。

【问题讨论】:

  • fileName 应该是String fileName = "C:\\FourLetterWords.txt"
  • 您的文字是如何存储在文本文件中的,它们是用 、空格等...分隔的吗?
  • 我看错了代码......所以我编辑了这个评论
  • @brso05 不,它们都在不同的行中。
  • @SuncoastOwner 关闭了 try 关键字。

标签: java arrays file-io try-catch


【解决方案1】:

试试这样的:

    String fileName = "C:\\FourLetterWords.txt";
    File fourLetterWords = new File(fileName);
    Scanner in = new Scanner(fourLetterWords);

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

    while (in.hasNextLine()) {
        words.add(in.nextLine());
    }

现在您的单词将存储在单词数组列表中,您可以使用随机数访问,例如:

    words.get(randomNumber);

【讨论】:

  • 我会试一试。
  • @NEPat10 等一下,你应该把ArrayList&lt;FourLetterWords&gt; 改成ArrayList&lt;String&gt; 我刚刚注意到了...
【解决方案2】:

由于整个随机数部分几乎只有一行代码,并且 getWord 方法在逻辑上不应该在提供随机数的类中,因此我将一个类放在一起来完成整个工作。

我建议也使文件名动态化(例如,向 RandomWordProvider 构造函数添加一个参数),但决定不这样做以使其更简单。

class RandomWordProvider {

    private List<String> words;

    public RandomWordProvider() {
        words = readFile();
    }

    private int randomInteger() {
        int randomInt = (int) (Math.random() * words.size());
        return randomInt;
    }

    public String getWord(int randomInt, String line) {
        int randomPosition = randomInteger();
        String randomWord = words.get(randomPosition);
        return randomWord;
    }

    private List<String> readFile() {

        List<String> wordsList = new ArrayList<>();

        try {
            String fileName = "C:/FourLetterWords.txt";
            File fourLetterWords = new File(fileName);
            Scanner in = new Scanner(fourLetterWords);

            while (in.hasNextLine()) {
                String line = in.nextLine();
                if (line!=null && !line.isEmpty()) {
                    wordsList.add(line);
                }
            }
        } catch (FileNotFoundException ex) {
            System.out.println("File not found.");
        }

        return wordsList ;
    }
}

我删除了对 getWord 的静态访问,因此您必须初始化对象并开始读取文件。

随机整数: 我更改了计算它的函数,因此它采用列表的大小,并且如果您以后想添加更多单词,它是灵活的。 方法 Math.random() 永远不会返回 1,因此对于您的 87 个元素,该数字将介于 0 和(在您的示例中)86.999 之间......其中转换为 int 只会截断小数部分。

getWord: 该方法获取一个随机值作为单词列表中的位置指示符。 然后它将随机单词从您的列表中取出并最终返回。

读取文件: 几乎你已经做了什么,我添加了对 null 和空字符串的检查,然后将单词添加到稍后返回的数组中。 据我所知,Java 不太关心您在路径中使用什么斜杠,我从依赖操作系统的路径切换到始终使用“普通”斜杠...

这是干编码的,所以我希望我没有遗漏任何内容,尤其是我没有检查使用扫描仪读取行的整个部分... :) 为了使其更易于理解,我决定编写一些不必要的代码,如果需要,randomInteger() 和 getWord() 可以在一行中完成;)

【讨论】:

    【解决方案3】:

    创建一个Strings 的数组(假设您将其命名为words[])。在程序开始时,从文件中逐行读取,并将它们存储在数组中(words[i++]=line)。现在,当您需要选择一个单词时,只需执行word = words[randomInt]

    【讨论】:

    • 数组是个坏主意,使用可以像 ArrayList 一样增长的东西。
    • 不,数组是个好主意!完美!
    • @Dima 如果您知道数组需要提前的大小,那么您是正确的。在这种情况下,用法表示 87 个单词,所以你是对的,他可以在这种情况下使用数组。
    • 写出 87 个字还是很痛苦的。我更愿意学习如何读取 .txt 文件
    • @NEPat10 为什么,是的。当然,从文本文件中读取它们。 words[i++] = in.next(); 会做
    猜你喜欢
    • 2016-03-04
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2019-08-17
    • 2021-12-27
    • 1970-01-01
    相关资源
    最近更新 更多