2014-07-08 3 views
-1

이 코드는 임의의 문자열을 반환하려는 경우이 코드를 사용하므로 매번 다른 문자열이 반환됩니다. 그것은Math.random()이 제대로 반환되지 않습니다.

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

그러나 수학 수업 방법을 사용하여 시도와 함께 잘 작동하고 그냥 인덱스 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; 
    } 
} 

답변

3

당신은뿐만 아니라 Math.random()

(int)Math.random() 항상 0이 그럼 당신은 sentenceStore.length에 0을 곱 반환 int에 전체를 캐스팅해야 결과는 0이 될 것입니다.

사용

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

우수한. 대단히 감사합니다. – user3814983

+0

당신은 환영합니다 – Phash

관련 문제