读取文本文件将其存储到数组中

时间:2012-06-06 12:39:12

标签: java

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

2 个答案:

答案 0 :(得分: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;
}

这样您就不需要有两个几乎相同的方法readFileIntoArray(2)

答案 1 :(得分:0)

如另一个答案所述,请使用扫描仪的正确语法。

另外,检查你的getNoun()和getAdjective()方法。我不确定它们会产生预期的结果,如果它们确实如此,它们看起来有点复杂。尝试这样的事情:

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

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

    return retVal;
}

Java数组的大小存储在实例变量length中。 nextInt(int upperBound)也需要一个上限。