更改双变量中的随机值?

时间:2021-06-03 22:33:02

I'm attempting to change a random value in a double. The chosen value is random for the length size of the variable. The method below returns the exact same parameter it takes. Any help please? I want it to return a new changed variable (just change element in the variable). Any help please?

我试图改变双重中的随机值。对于变量的长度大小,所选值是随机的。下面的方法返回完全相同的参数。有什么帮助吗?我希望它返回一个新的变更变量(只需更改变量中的元素)。有什么帮助吗?

public static double changeRandomValue(double currentVel) {


        String text = Double.toString(Math.abs(currentVel));
        int integerPlaces = text.indexOf('.');
        int decimalPlaces = text.length() - integerPlaces - 1;
        int nn = text.length();
        //rand generates a random value between 0 and nn
        int p = rand(0,nn-1);

        char ppNew = (char)p;

        StringBuilder sb = new StringBuilder(text);
        if (text.charAt(ppNew) == '0') {
            sb.setCharAt(ppNew, '1');
        } else if (text.charAt(ppNew) == '1'){
            sb.setCharAt(ppNew, '2');
        } else if (text.charAt(ppNew) == '2') {
            sb.setCharAt(ppNew, '3');
        } else if (text.charAt(ppNew) == '3') {
            sb.setCharAt(ppNew, '4');
        } else if (text.charAt(ppNew) == '4') {
            sb.setCharAt(ppNew, '5');
        } else if (text.charAt(ppNew) == '5') {
            sb.setCharAt(ppNew, '6');
        } else if (text.charAt(ppNew) == '6') {
            sb.setCharAt(ppNew, '7');
        } else if (text.charAt(ppNew) == '7') {
            sb.setCharAt(ppNew, '8');
        } else if (text.charAt(ppNew) == '8') {
            sb.setCharAt(ppNew, '9');
        } else {
            sb.setCharAt(ppNew, '0');
        }
        double newText = Double.parseDouble(text);
        return newText;
    }

1 个解决方案

#1


2  

Changing the StringBuilder doesn't change the original String it was made from.

更改StringBuilder不会更改它的原始字符串。

You do this:

你做这个:

StringBuilder sb = new StringBuilder(text);

then change sb, then do this:

然后改变某人,然后这样做:

double newText = Double.parseDouble(text);

which still uses the original text.

它仍然使用原始文本。

You can get the modified String from the StringBuilder using its toString method. Change that line to:

您可以使用其toString方法从StringBuilder获取修改后的String。将该行更改为:

double newText = Double.parseDouble(sb.toString());

#1


2  

Changing the StringBuilder doesn't change the original String it was made from.

更改StringBuilder不会更改它的原始字符串。

You do this:

你做这个:

StringBuilder sb = new StringBuilder(text);

then change sb, then do this:

然后改变某人,然后这样做:

double newText = Double.parseDouble(text);

which still uses the original text.

它仍然使用原始文本。

You can get the modified String from the StringBuilder using its toString method. Change that line to:

您可以使用其toString方法从StringBuilder获取修改后的String。将该行更改为:

double newText = Double.parseDouble(sb.toString());