以下代码在 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 参数并将每个文本文件放在那里。所以我的运行参数说adjectives.txt
,nouns.txt
(每个文件都是 10 个名词或形容词的列表)。
我想将它们存储到数组中,然后让程序从每个列表中随机选择一个并发表声明。