簡體   English   中英

讀取文本文件並將其存儲到數組中

[英]reading text file storing it into an array

以下代碼在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個名詞或形容詞的列表)。
我想將它們存儲到數組中,然后讓程序從每個列表中隨機選擇一個並聲明。

您應該使用new Scanner(new File("adjectives.txt")) 另外,由於您需要使用命令參數-請使用它們! 包含文件名並返回字符串數組的Write方法:

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)

如另一個答案中所述,為掃描儀使用正確的語法。

另外,檢查您的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)也需要一個上限。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM