2014-03-12 105 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