如何将VB代码转换为Java

时间:2014-08-26 02:29:53

标签: java vb.net

我正在尝试将这些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;
    }

2 个答案:

答案 0 :(得分:0)

您只需创建Random一次。从那时起,调用nextIntnextDouble将返回随机数。您还需要使用双精度而不是整数,以便计算值不会舍入为整数。

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

}