다음 코드는 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 개의 명사 또는 형용사의 목록입니다)이라고 나와 있습니다.
배열에 저장 한 다음 각 목록에서 무작위로 하나를 선택하고 문을 작성하는 프로그램을 가져 오려고합니다.