我是java編程的初學者,正在通過Ex。 Deitel的16.5(隨機句)& Deitel並且問題要求用從文章,名詞,動詞和介詞的給定排列中隨機選擇的詞形成句子,以形成20個句子,其中句子必須按以下順序形成:文章,名詞,動詞,prep,文章和名詞。 它要求在單詞之間留出空格,我不知道該怎麼做。此外,我已經以非常錯誤的方式串聯字符串,因此非常感謝您的幫助和指導。從給定數組中隨機選擇單詞以形成句子
import java.util.*;
public class Makeit{
private static String[] article ={"the","a","one","some","any"};
private static String[] noun={" boy"," girl"," dog"," town"," car"};
private static String[] verb={" drove"," jmped"," ran"," walked"," skipped"};
private static String[] preposition={" to"," from"," over"," under"," on"};
public static void main(String args[]){
//order to make a sent: a,n,v,p,a,n
System.out.println("the sentences picked at random are:");
//loop to generate 20 sentences
for(int i=0;i<=19;i++){
System.out.println(makeSentence());
}
}
public static String makeSentence(){
Random rand = new Random();
int[] index = new int[6];
String sent = new String();
for(int i=0;i<6;i++){
index[i]= rand.nextInt(5);
}
sent = sent.concat(article[index[0]].concat(noun[index[1]].concat(verb[index[2]].concat(preposition[index[3]].concat(article[index[4]].concat(noun[index[5]]))))));
return sent;
}
}
他們在這一點上是否已經討論過'StringBuilder'?使用顯式字符串構建器的 – user1803551
@ user1803551在此處不是必需的。編譯多個使用'+'的連接以在內部使用StringBuilder,但它明確地使用它只是語法混亂。 –
是的,他們做到了,但我還沒有充分相信這個班級如此不願意使用它......謝謝 –