有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带逗号的java数字字符串

我在解决此问题时遇到问题:

Write a structures program that can accept two integer numbers up to 40 digit and perform the following:

  1. add the two numbers together and display the result
  2. the result number should should be seperated by commas.

所以我可以使用BigInteger做第一件事,但是对于第二部分,我遇到了一些问题。我不知道应该如何在字符串中添加逗号,我使用了for循环来处理split,但它不起作用

我想起来了谢谢你的帮助

   public static String NewString (String num)
   {
    String sent = "" ;
    int count = 0;
        for ( int index = num.length()-1 ; index >= 0 ; index --)
        {
       count++;
           sent = num.charAt(index) + sent;
       if(count % 3 == 0 && index != 0) 
       sent = "," + sent;
        }
      return sent;
   }

共 (2) 个答案

  1. # 1 楼答案

    你可以用

    String formattedInteger = NumberFormat.getNumberInstance(Locale.US).format(bigInteger);
    

    或者你也可以自己写。这将非常简单,只需将BigInteger转换为String,然后向后循环,每传递第三个字符添加一个逗号

  2. # 2 楼答案

    以下代码:

    • 将两个数字相加并显示结果
    • 结果编号应以逗号分隔

    这是不言自明的,希望这有帮助:)

    package stackoverflow;
    
    import java.math.BigInteger;
    
    /**
     * Created by Nick on 11/13/14.
     *
     * Add two numbers together and display the result
     * The result number should be separated by commas.
     */
    public class SO_26916958 {
    
    private static BigInteger arg1;
    private static BigInteger arg2;
    
    public static void main(String[] args) {
        arg1 = new BigInteger (args[0].getBytes());
        arg2 = new BigInteger (args[1].getBytes());
        BigInteger sum = arg1.add(arg2);
        String bigIntegerString = sum.toString();
    
        String output = recursivelyAddComma(bigIntegerString);
    
        System.out.print(bigIntegerString +"\n");
        System.out.print(output);
    }
    
    private static String recursivelyAddComma (String s) {
        int length = s.length();
        StringBuilder output = null;
    
        if(length <= 3) {
            return s.toString();
        }
    
        return  recursivelyAddComma(s.substring(0, length - 3)).concat(",").concat(s.substring(length - 3, length));
    
        }
    
    }