2013-12-10 83 views
-1

我被要求創建一個提示用戶輸入最小值和最大值的GUI。使用輸入的值,我想在兩者之間生成一個隨機整數。到目前爲止,我有下面的內容,但是我如何確保生成的整數在兩者之間,我迷失了方向。如果最小數字是0並且最大數字是任何東西,我可以得到正確的輸出,但是如果最小數字超過那個數字,則不能。謝謝!在兩個用戶輸入值之間生成一個整數

private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {            
    double minNumber, maxNumber, randomValue, outputValue; 

    //Get the string data entered and parse it to numerical data 
    minNumber = Double.parseDouble(minInput.getText()); 
    maxNumber = Double.parseDouble(maxInput.getText()); 

    //create a random value to multiply off of. 
    randomValue = (Math.random()); 

    //generate random output value. 
    outputValue = (randomValue*maxNumber); 

    //output the ranomly generated number to the outputLabel on the GUI. 
    outputLabel.setText("The random value generated is: " + outputValue); 
+0

在'0'和'1'之間生成一個隨機數,稱之爲'x'。然後計算'min + x *(max-min)'。 –

+1

使用谷歌搜索會比發佈這個問題更快...... – Andrew

回答

1
//generate random output value. 
outputValue = randomValue*(maxNumber - minNumber)+minNumber; 
+0

這對於發佈者的目的來說可能已經足夠了,但它對於最終值有點偏向。 –

1

要獲得你算算它這樣你的隨機值:

randomValue = (Math.random() % (maxNumber - minNumber)) + minNumber; 

順便說一句,這個問題已經討論過了here