2014-07-08 183 views
-1

我有這個代碼,我想要隨機返回字符串,因此每次都會返回一個不同的字符串。它的工作原理罰款Math.random()沒有正確返回

words = sentenceStore[rnd.nextInt(sentenceStore.length)]; 

,但試圖利用數學類的方法,它只是返回每次

words = sentenceStore[(int)Math.random() * sentenceStore.length]; 

誰能幫助索引0的字符串?

WordBank.java(無主此方法):

import java.util.Random; 

public class WordBank { 

    private String [] sentenceStore; 

    public String getSentence (String words) { 

     String [] sentenceStore = new String [5]; //i'll store 5 sentences here for now. 

     sentenceStore[0] = "Hello how are you doing"; 
     sentenceStore[1] = "What do you want eh"; 
     sentenceStore[2] = "Hello can i help you"; 
     sentenceStore[3] = "You are so incredibly pretty"; 
     sentenceStore[4] = "What was that you said"; 

     Random rnd = new Random(); 

     words = sentenceStore[rnd.nextInt(sentenceStore.length)]; 

     //words = sentenceStore[(int)Math.random() * sentenceStore.length]; 

     return words; 
    } 
} 

回答

3

你必須投整件事int,不僅Math.random()

(int)Math.random()總是返回0,然後你sentenceStore.length乘以0,這也會導致0。

使用

words = sentenceStore[(int) (Math.random() * sentenceStore.length)]; 
+0

優秀。非常感謝你。 – user3814983

+0

不用客氣 – Phash