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");

これにより、改行ごとに文字列が分割されるため、これがテキストファイルであると想定します。

Word1

Word2

Word3

単語は次のようになります:{word1、word2、word3}

于 2012-08-24T05:23:47.070 に答える
1

読んでいる単語がファイルの各行に保存されている場合は、hasNextLine()とを使用しnextLine()て一度に1行ずつテキストを読むことができます。next()配列に1つの単語を投げるだけでよいので、willを使用することもできますnextLine()が、通常は常に推奨されます。

配列のみを使用する場合は、次の2つのオプションがあります。

  • 大きな配列を宣言します。そのサイズは、単語の総数より少なくなることはありません。
  • 最初に要素の量を読み取るときにファイルを2回調べ、次にその値に応じて配列を初期化し、次に文字列を追加しながらもう一度ファイルを調べます。

通常、 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++;

正直なところ、この例はあまり意味がないので、これら2つの例を実行しました

1つ目は、Alexが提案した概念を使用しており、ファイルから不明な行数を読み取ることができます。

唯一のトリップアップは、行が複数の1行フィードで区切られている場合です(つまり、単語間に余分な行があります)

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) {
        }
    }

}

2つ目は、単語を既知の長さの配列に読み取る方法を示しています。これはおそらくあなたが実際に欲しいものに近いです

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) {
        }
    }

}

これらのいずれかが役立つと思われる場合は、私が採用したのは彼の考えであるため、私に小さな賛成票を投じて、アレックスの答えが正しいかどうかを確認することをお勧めします。

これで、使用する改行について本当に心配している場合は、値を介してシステムで使用されている値を見つけることができますSystem.getProperties().getProperty("line.separator")

于 2012-08-24T23:22:57.987 に答える