Math.random()没有正确返回

时间:2014-07-08 05:56:42

标签: java variables casting

我有这个代码,我想要返回随机完成的String字符,这样每次都会返回不同的字符串。它适用于

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

但是尝试使用Math类方法,它每次只返回索引0的字符串

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

有人可以帮忙吗?

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

1 个答案:

答案 0 :(得分:3)

您必须将整个内容转换为int,而不仅仅是Math.random()

(int)Math.random()始终返回0.然后将0与sentenceStore.length相乘,这也将导致0。

使用

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