0

我需要编写一个生成随机俳句的程序。我的计划是让程序读取包含指定数量的音节名词、动词和形容词的文件,但我遇到了编码问题。现在它看起来像这样:

package poetryproject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;



public class PoetryProject {

    public static void main(String[] args) throws FileNotFoundException {


        Random gen = new Random();

        Scanner adjectivesFile = new Scanner(new File("AdjectivesFile.dat"));
        Scanner nounFile = new Scanner(new File("NounFile.dat"));
        Scanner verbFile = new Scanner(new File("VerbFile.dat"));

        int adjectiveCount = adjectivesFile.nextInt();
        String[] adjectiveList = new String[adjectiveCount];
        for (int i = 0; i < adjectiveCount; i++) {
            adjectiveList[i] = adjectivesFile.nextLine();
        }
        adjectivesFile.close();

        int nounCount = nounFile.nextInt();
        String[] nounList = new String[nounCount];
        for (int i = 0; i < nounCount; i++) {
            nounList[i] = nounFile.nextLine();
        }
        nounFile.close();

        int verbCount = verbFile.nextInt();
        String[] verbList = new String[verbCount];
        for (int i = 0; i < verbCount; i++) {
            verbList[i] = verbFile.nextLine();
        }
        verbFile.close();

        for (int count = 1; count <= 1; count++) {
           System.out.printf("The %s %s \n",       adjectiveList[gen.nextInt(adjectiveList.length)]);
        }
        for (int count = 1; count <= 1; count++) {
            System.out.printf("%s %s \n", nounList[gen.nextInt(nounList.length)]);
        }
        for (int count = 1; count <= 1; count++) {
            System.out.printf("%s %s \n", verbList[gen.nextInt(verbList.length)]);
        }
     }
}

对于我的输出,我只得到“The”形容词部分。为什么是这样?

哦,是的,我目前只致力于让第一行正确打印。

4

2 回答 2

4

第一个的格式说明符printf()与参数不匹配:

System.out.printf("The %s %s \n", adjectiveList[gen.nextInt(adjectiveList.length)]);

MissingFormatArgumentException这将在打印形容词部分后抛出一个过早地结束您的程序。

于 2013-04-10T19:21:12.220 回答
1

由于您没有为 System.out.printf 指定第二个参数,因此它会在以下行生成找不到符号错误:

System.out.printf("The %s %s \n",adjectiveList[gen.nextInt(adjectiveList.length)]);
                          ^

删除第二个格式说明符并将其编写为:

System.out.printf("The %s\n",       adjectiveList[gen.nextInt(adjectiveList.length)]);

这应该可以解决您的问题。

于 2013-04-10T19:27:19.840 回答