2015-04-12 46 views
0

我認爲我的算法出了問題,我試圖將我的 數字150000拆分爲數千個for循環。我想要輸出爲150,000。 我只是有麻煩提出一個很好的方式做到這一點。關於將數字拆分爲數千

這裏是我的代碼:

public class testing { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     String l= "150000"; 
     for(int i=l.length();i<0;i--){ 
      if ((i/4)==0){ 
       l=","+l.substring(i, l.length()-1); 
      } 
     } 
     System.out.println(l); 
    } 

} 
+0

http://stackoverflow.com/a/3672738/1897935 –

+0

您是否必須手動執行此操作,或者可以使用可用的工具嗎? – Pshemo

+0

可能的重複[如何格式化一個字符串數字以逗號和舍入?](http://stackoverflow.com/questions/3672731/how-can-i-format-a-string-number-to-have-逗號和輪) – kdopen

回答

2

我要輸出到像150,000。我剛剛遇到了問題 與一個很好的方式做它

使用DecimalFormat並設置DecimalFormatSymbols分組分隔符:

DecimalFormatSymbols symbol = new DecimalFormatSymbols(); 
symbol.setGroupingSeparator(','); 
DecimalFormat format = new DecimalFormat(); 
format.setDecimalFormatSymbols(symbol); 
System.out.println(format.format(150000));//print 150,000 

編輯

根據您的意見,如果你真的想用一個循環,在此一說將工作:

String l = "150000"; 
String result = ""; 
for (int i = 0; i < l.length(); i++) { 
    if (i != 0 && i % 3 == 0) 
     result = result + "," + l.charAt(i); 
    else 
     result = result + l.charAt(i); 
} 
System.out.println(result); 

這將打印150,000

您的實際循環從未達到的條件爲i < 0,但我在l.length()開始它永遠不能小於0。i/4也是錯誤的,你想用模來代替。我也相信它應該是i % 3而不是i % 4。你還需要檢查這是否是字符串的開始,否則它會在開始時輸入一個逗號。

+0

我看到你在那裏做了什麼。不幸的是,我不能在課堂上爲我的項目使用格式化功能。我不得不用for循環和子串來手動將數字分成數千個。謝謝你的方式。 –

+0

@NateLee編輯我的答案。 –