2014-03-12 112 views
0

我正在尝试在double中更改一个随机值。所选值对于变量的长度大小是随机的。下面的方法返回完全相同的参数。请帮忙吗?我希望它返回一个新的变化的变量(只是改变变量中的元素)。请帮忙吗?更改双变量中的随机值?

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

回答

2

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

你这样做:

StringBuilder sb = new StringBuilder(text); 

然后更改sb,那么这样做:

double newText = Double.parseDouble(text); 

它仍然使用原来的文本。

您可以使用其toString方法从StringBuilder中获取修改的字符串。将该行更改为:

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

非常好,非常感谢! – Adz