0

次のコードは jgrasp でコンパイルされますが、You null null. テキスト ファイルを読み取って配列に格納する方法がわかりません。

import java.io.*; 
import java.util.Scanner;
import java.util.Random;
public class InsultGenerator {

//randomly picks an adjective and a noun from a list of 10 random nouns and adjectives
//it then creates a random insult using one adjective and one noun
public static void main (String [] args)throws IOException
{
    String[]adjectives = new String [10];
    String[]nouns = new String [10];
    int size = readFileIntoArray (adjectives);
    int size2 = readFileIntoArray2 (nouns);
        String adjective = getAdjective(adjectives, size);
    String noun = getNoun(nouns, size2);
    printResults(adjectives, nouns, adjective, noun );
}

public static int readFileIntoArray (String[] adjectives)throws IOException
{  
    Scanner fileScan= new Scanner("adjectives.txt");
    int count = 0;  
    while (fileScan.hasNext()) 
    {
        adjectives[count]=fileScan.nextLine();
        count++;
    }
    return count;
}
public static int readFileIntoArray2(String[] nouns)throws IOException
{
    Scanner fileScan= new Scanner("nouns.txt");
    int count = 0;  

    while (fileScan.hasNextLine()) 
    {
        nouns[count]=fileScan.nextLine();
        count++;
    }   
    return count;
}
public static String getAdjective(String [] adjectives, int size)
{
    Random random = new Random();
    String adjective = "";
    int count=0;
    while (count < size)
    {
        adjective = adjectives[random.nextInt(count)]; 
        count ++;
    }
    return adjective;
}
public static String getNoun(String[] nouns, int size2)
{
    Random random = new Random();
    String noun = "";
    int count=0;
    while (count < size2)
    {
        noun = nouns[random.nextInt(count)]; 
        count ++;
    }
    return noun;
}
public static void printResults(String[] adjectives, String[] nouns, String adjective, String noun) 
{
    System.out.println("You " + adjective + " " + noun);
}
}

先生は、run 引数を使用して、各テキスト ファイルをそこに入れることを望んでいます。したがって、私の run 引数はadjectives.txtnouns.txt(これらのファイルのそれぞれは 10 個の名詞または形容詞のリストです) と述べています。
それらを配列に保存し、プログラムに各リストからランダムに1つを選択してステートメントを作成させたいと思います。

4

2 に答える 2

1

を使用する必要がありますnew Scanner(new File("adjectives.txt"))。また、コマンド引数を使用する必要があるため、それらを使用してください! ファイル名を受け取り、文字列の配列を返す書き込みメソッド:

public String[] readLines(String filename) throws IOException {
    String[] lines = new String[10];
    Scanner fileScan= new Scanner(new FIle(filename));
    // read lines
    // ...
    return lines;
}

この方法では、ほぼ同じメソッドを 2 つ持つ必要はありませんreadFileIntoArray(2)

于 2012-06-06T12:46:39.027 に答える
0

別の回答で述べたように、スキャナーには正しい構文を使用してください。

また、getNoun() および getAdjective() メソッドを確認してください。期待どおりの結果が得られるかどうかはわかりません。もしそうなら、少し複雑に思えます。次のようなことを試してください:

public static String getString(String[] str) {      
    Random rand = new Random();

    String retVal = str[rand.nextInt(str.length)];

    return retVal;
}

Java 配列のサイズは、インスタンス変数に格納されていますlengthnextInt(int upperBound)上限も必要です。

于 2012-06-06T13:03:01.250 に答える