我正在尝试将这些VB函数转换为Java。这就是我到目前为止所做的。我在获取nRandom
时遇到问题,它始终会返回nLow
的值,我怀疑这是R
因为我打印R
它始终给出答案0.0
问题:我的Java代码有什么问题?
VB代码
Function GetRandom(ByVal nLow As String, ByVal nHigh As String) As String
Static boolStarted As Boolean
Dim nRandom As String
If Not boolStarted Then
Randomize(Second(Now) / 100)
Rnd()
End If
nRandom = Int((nHigh - nLow + 1) * Rnd() + nLow)
GetRandom = nRandom
End Function
JAVA CODE
private String GetRandom(String nLow, String nHigh)
{
boolean boolStarted=false;
String nRandom;
Date date=new Date();
double R=0;
if(boolStarted==false)
{
Random rnd=new Random();
//R=rnd.nextInt(Math.round(date.getSeconds()/100));
//R=rnd.nextDouble();
R=Math.round(Integer.valueOf(date.getSeconds())/100);
}
System.out.println("Random: "+R);
System.out.println("SEC: "+date.getSeconds());
nRandom=String.valueOf((Integer.valueOf(nHigh)-Integer.valueOf(nLow)+1)*R+Integer.valueOf(nLow));
return nRandom;
}
答案 0 :(得分:0)
您只需创建Random
一次。从那时起,调用nextInt
或nextDouble
将返回随机数。您还需要使用双精度而不是整数,以便计算值不会舍入为整数。
public class RandomGenerator
{
private Random _r = new Random();
private String GetRandom(String nLow, String nHigh)
{
double low = Double.Parse(nLow);
double high = Double.Parse(nHigh);
double R = _r.nextDouble();
string nRandom = ((high - low + 1) * R + low).ToString();
return nRandom;
}
}
答案 1 :(得分:0)
import java.util.Random;
class GetRandom {
String GetRandom(String nLow, String nHigh) {
Random ran = new Random();
double low = Double.parseDouble(nLow);
double high = Double.parseDouble(nHigh);
return ("" + ((high - low) * ran.nextDouble() + low));
}
public static void main(String[] args) {
GetRandom s = new GetRandom();
String nLow = "2.5805"; // Lower value you want
String nHigh = "80.5454"; // Higher value you want
System.out.println(s.GetRandom(nLow, nHigh));
}
}