2013-08-03 65 views
-5

一串挣扎这里是我的代码我与创建一个随机单词,而不是单词

我得到的话,而不是只是一个字符串,我想我已经完全做到了。如果你能给我一些很棒的指针,我将所有的代码包含进去的唯一原因是我可能看过的东西,我认为它与构建这个短语有关,但我不确定

//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)"); 

    } 

} 

回答

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); 
+0

谢谢,这真是帮了:) – user2648747

1

更好的加号 “+” 运算符连接产生一个词串。初始化字符串数组时,请使用逗号作为分隔符。

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" 
    }; 
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)]); 
相关问题