次のコードは 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.txt
、nouns.txt
(これらのファイルのそれぞれは 10 個の名詞または形容詞のリストです) と述べています。
それらを配列に保存し、プログラムに各リストからランダムに1つを選択してステートメントを作成させたいと思います。