2015-06-30 62 views
0

我想將我的浮點值轉換爲整數,但我無法將其轉換。它說不能找到符號。有沒有辦法做到這一點。Java數學轉換爲整數

這是我的Java代碼:

float upper = 999999; 
float lower = 100000; 
Integer ReceiptNo = 0; 

Random rnd = new Random(); 
ReceiptNo = Math.round((Math.floor((upper - lower + 1) * rnd()))) + lower; 

這是我的VB代碼:

Dim upper As Single = 999999  'Set the upper limit of random number. 
Dim lower As Single = 100000 
Dim ReceiptNo As Integer = 0 

Randomize()  'Need to randomise the random number or else the number generated is always the same 
ReceiptNo = CInt(Math.Floor((upper - lower + 1) * Rnd())) + lower 

我想重用在Java VB代碼。謝謝。

+0

見我的回答對VB,注意上是唯一的,因此需要在1以上的最大值。 – dbasnett

回答

1

rnd是一個實例變量,而不是一個方法,所以你不能寫rnd()

你可以寫:

ReceiptNo = (int)(Math.round((Math.floor((upper - lower + 1) * Math.random()))) + lower); 

我不知道什麼Rnd()確實在VB中,但如果它產生在0和1之間的隨機雙,那是什麼呢Math.random()

+0

那麼我該怎麼做和VB一樣?因爲我在網站上看到有這樣的一種方式... 隨機randomGenerator = new Random(); (int idx = 1; idx <= 10; ++ idx){ int randomInt = randomGenerator.nextInt(100); log(「Generated:」+ randomInt);' – raaj5671

+0

它說浮動不能轉換爲整數 – raaj5671

+0

@ raaj5671對不起,添加一個轉換爲int - '(int)'。 – Eran

0

使用Math.random()而不是rnd()。 您需要從Math.round值(它返回float)轉換爲int

ReceiptNo = (int) (Math.round((Math.floor((upper - lower + 1) * Math.random()))) + lower); 
0
Dim prng As New Random 'do NOT put this in a method 
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 
    Dim upper As Integer = 999999 + 1  'Set the upper limit of random number. 
    Dim lower As Integer = 100000 
    Dim ReceiptNo As Integer = prng.Next(lower, upper) 'the upper is exclusive 
End Sub