2013-04-10 64 views
0

我需要編寫一個程序來生成隨機的Haikus。我的計劃是讓程序讀取包含指定數量的音節名詞,動詞和形容詞的文件,但是我在編碼時遇到問題。現在它看起來是這樣的:Haiku Generator Java

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)]); 
     } 
    } 
} 

對於我的輸出,我只得到了「的」形容詞一部分。爲什麼是這樣?

哦,是的,我只是努力讓第一行正確打印。

+0

'gen'在哪裏定義? – gparyani 2013-04-10 19:22:04

+0

Random gen = new Random(); – user2149738 2013-04-10 19:23:20

回答

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)]); 

這應該解決您的問題。

4

第一printf()的格式說明不匹配參數:

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

,這將拋出一個MissingFormatArgumentException,提前結束你的程序打印形容詞部分之後。

+0

我該如何解決這個問題? – user2149738 2013-04-10 19:24:13

+0

該方法正在等待2個參數進行格式化,並且只傳遞1,即列表中的形容詞。除去'%s'或者在形容詞之後添加另一個參數。 – 2013-04-10 19:26:50

+0

那當然很容易。謝謝! – user2149738 2013-04-10 19:29:12