这是我的代码
我得到了一串单词,而不仅仅是一个单词,我认为我完成了它。如果你可以给我一些很棒的指针,我包含所有代码的唯一原因是我可能已经看了一些东西,我认为它与短语的构建有关但我不确定
//import java libraries
import java.awt.*;
import javax.swing.*;
public class Emotion extends JFrame
{
//set what you can use
private JLabel label;
private JLabel phrasem;
public Emotion()
{
setLayout( new FlowLayout());
//Wordlists
String[] wordlistone =
{
"anger","misery"+"sadness"+"happiness"+"joy"+"fear"+"anticipation"+"surprise"+"shame"+"envy"+"indignation"+"courage"+ "pride"+"love"+"confusion"+"hope"+"respect"+"caution"+"pain"
};
//number of words in each list
int onelength = wordlistone.length;
//random number
int rand1 = (int) (Math.random() * onelength);
//building phrase
String phrase = wordlistone[rand1];
// printing phrase
phrasem = new JLabel("PhraseOMatic says:");
add (phrasem);
label = new JLabel("Today you emotion is: " + phrase);
add (label);
}
public static void main(String[] args)
{
Emotion gui = new Emotion();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(400, 100);
gui.setVisible(true);
gui.setTitle("My App (Alex Gadd)");
}
}
答案 0 :(得分:2)
您有+
,您应该在单词列表中有,
我想你只是误解了那两个。
String[] wordlistone = {
"anger", "misery", "sadness", "happiness", "joy", "fear", "anticipation",
"surprise", "shame", "envy", "indignation", "courage", "pride", "love",
"confusion", "hope", "respect", "caution", "pain"
};
此外,您可以使用java.util.Random轻松获得随机int,它优于Math.random()
Random rand = new Random();
int i = rand.nextInt(wordlistone.length);
答案 1 :(得分:1)
加号“+”运算符连接只产生一个单词的字符串。初始化字符串数组时,使用逗号作为单词分隔符。
答案 2 :(得分:1)
您的单词列表数组只有两个元素。您在第一个和第二个之间使用了逗号,然后通过与其余单词串联意外地创建了一个大字符串。改变这个:
String[] wordlistone =
{
"anger","misery"+"sadness"+"happiness"+"joy"+"fear"+"anticipation"+"surprise"+"shame"+"envy"+"indignation"+"courage"+ "pride"+"love"+"confusion"+"hope"+"respect"+"caution"+"pain"
};
到此
String[] wordlistone =
{
"anger", "misery", "sadness", "happiness", "joy", "fear", "anticipation", "surprise", "shame", "envy", "indignation", "courage", "pride", "love", "confusion", "hope", "respect", "caution", "pain"
};
答案 3 :(得分:1)
两个观察结果:
array
包含连续的String
值,因此您应将+
替换为,
Random
对象 - Math.random() * wordlistone.length
无效这是我的版本:
String[] wordlistone = {
"anger","misery","sadness","happiness","joy","fear","anticipation","surprise","shame","envy",
"indignation","courage", "pride","love","confusion","hope","respect","caution","pain"
};
Random r = new Random(); // you can reuse this - no need to initialize it every time
System.out.println(wordlistone[r.nextInt(wordlistone.length)]);