0

我需要将此文件打印到一个数组,而不是屏幕上。是的,我必须使用一个数组 - 学校项目 - 我对 java 很陌生,所以感谢任何帮助。有任何想法吗?谢谢

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class HangmanProject
{
    public static void main(String[] args) throws FileNotFoundException
    {

        String scoreKeeper;     // to keep track of score
        int guessesLeft;        // to keep track of guesses remaining
        String wordList[];    // array to store words


        Scanner keyboard = new Scanner(System.in);    // to read user's input

        System.out.println("Welcome to Hangman Project!");

        // Create a scanner to read the secret words file
        Scanner wordScan = null;

        try {
            wordScan = new Scanner(new BufferedReader(new FileReader("words.txt")));
            while (wordScan.hasNext()) {
                System.out.println(wordScan.next());
            }
        } finally {
            if (wordScan != null) {
                wordScan.close();
            }
        }
    }
}
4

3 回答 3

1

您是否需要更多帮助来读取文件或将字符串放入已解析的数组?如果您可以将文件读入字符串,只需执行以下操作:

String[] words = readString.split("\n");

这将在每个换行符处拆分字符串,因此假设这是您的文本文件:

字1

字2

字3

单词将是:{word1,word2,word3}

于 2012-08-24T05:23:47.070 回答
1

如果您正在阅读的单词存储在文件的每一行中,您可以使用hasNextLine()andnextLine()一次读取一行文本。使用next()will 也可以,因为您只需要在数组中输入一个单词,但nextLine()通常总是首选。

至于仅使用数组,您有两种选择:

  • 你要么声明一个大数组,你确定它的大小永远不会小于总字数;
  • 您浏览文件两次,第一次读取元素的数量,然后根据该值初始化数组,然后在添加字符串的同时再次浏览它。

通常建议使用动态集合,例如ArrayList()。然后,您可以使用toArray()方法将列表转换为数组。

于 2012-08-24T05:31:29.117 回答
1

尼克,你刚刚给了我们最后一块拼图。如果您知道要读取的行数,则可以在读取文件之前简单地定义一个该长度的数组

就像是...

String[] wordArray = new String[10];
int index = 0;
String word = null; // word to be read from file...
// Use buffered reader to read each line...
    wordArray[index] = word;
    index++;

说实话,这个例子没什么意义,所以我做了这两个例子

第一个使用 Alex 建议的概念,它允许您从文件中读取未知数量的行。

唯一的问题是,如果行被多个换行符分隔(即单词之间有额外的行)

public static void readUnknownWords() {

    // Reference to the words file
    File words = new File("Words.txt");
    // Use a StringBuilder to buffer the content as it's read from the file
    StringBuilder sb = new StringBuilder(128);

    BufferedReader reader = null;
    try {

        // Create the reader.  A File reader would be just as fine in this
        // example, but hay ;)
        reader = new BufferedReader(new FileReader(words));
        // The read buffer to use to read data into
        char[] buffer = new char[1024];
        int bytesRead = -1;
        // Read the file to we get to the end
        while ((bytesRead = reader.read(buffer)) != -1) {

            // Append the results to the string builder
            sb.append(buffer, 0, bytesRead);

        }

        // Split the string builder into individal words by the line break
        String[] wordArray = sb.toString().split("\n");

        System.out.println("Read " + wordArray.length + " words");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
        }
    }

}

第二个演示如何将单词读入已知长度的数组中。这可能更接近你真正想要的

public static void readKnownWords() 

    // This is just the same as the previous example, except we
    // know in advance the number of lines we will be reading    
    File words = new File("Words.txt");

    BufferedReader reader = null;
    try {

        // Create the word array of a known quantity
        // The quantity value could be defined as a constant
        // ie public static final int WORD_COUNT = 10;
        String[] wordArray = new String[10];

        reader = new BufferedReader(new FileReader(words));
        // Instead of reading to a char buffer, we are
        // going to take the easy route and read each line
        // straight into a String
        String text = null;
        // The current array index
        int index = 0;
        // Read the file till we reach the end
        // ps- my file had lots more words, so I put a limit
        // in the loop to prevent index out of bounds exceptions
        while ((text = reader.readLine()) != null && index < 10) {

            wordArray[index] = text;
            index++;

        }

        System.out.println("Read " + wordArray.length + " words");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
        }
    }

}

如果您发现其中任何一个有用,我会适当地使用它,您会给我一个小小的赞成票并检查亚历克斯的答案是否正确,因为我已经适应了他的想法。

现在,如果您对使用哪个换行符非常偏执,您可以通过 value 找到系统使用的System.getProperties().getProperty("line.separator")值。

于 2012-08-24T23:22:57.987 回答