创建一个toString方法以返回Java中的数组

时间:2018-12-23 20:08:49

标签: java arrays tostring

最近有人要求我编写一个toString方法,该方法返回数组中的数字,如下所示:

  

在数字右边每三位数后   添加一个逗号,但是如果该数字的位数为3或更少   不会添加逗号。

但是我遇到了一个问题:该方法总是返回值0,。如何调整代码以返回正确的格式?

public class BigNum {

    int[] num;
    final int MAX_DIGITS = 50;


    public BigNum() {
        this.num = new int[MAX_DIGITS];
        this.num[0] = 0;
        for(int i=1 ; i<this.num.length ; i++) 
            this.num[i] = -1;
    }

    public BigNum(long n) {

        int number = (int)n;
        this.num = new int[MAX_DIGITS];
        for (int i = 0; i < this.num.length; i++) {
            num[i] = number % 10;
            number /= 10; 
        }
    }

    public String toString(){

    String toReturn = "";
        this.num = new int[MAX_DIGITS];

        for(int i=0 ; i<this.num.length ; i++)
            if(this.num.length>=1 && this.num.length<=3)
                toReturn = num[i] + "";

        for(int j=0 ; j<this.num.length ; j+=3)
            toReturn = num[j] + "," ;


        return toReturn;
    }

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码。记住要复制BigNum构造函数。对以下代码进行了以下更改:

  1. 创建实例数组的长度等于输入中的位数,但不等于MAX_DIGITS。

  2. 更改了toString方法。

    public BigNum(long n) {
    
    int number = (int)n;
    int[] tempNum = new int[MAX_DIGITS];
    
    int counter=0;
    while(number>0) {
        tempNum[counter] = number % 10;
        number /= 10; 
        counter++;
    }
    this.num = Arrays.copyOfRange(tempNum, 0, counter);
    
    }
    
    public String toString(){
    String toReturn = "";
    if(this.num.length>=1 && this.num.length<=3) {
        for(int i=this.num.length-1 ; i>=0 ; i--) {
            toReturn += num[i];
        }
    }else {
        int commaPos = this.num.length%3==0?3:this.num.length%3;
        int counter=0;
        while(counter<this.num.length) {
            if(counter==commaPos) {
                toReturn+=",";
                commaPos+=3;
            }
            toReturn+=num[this.num.length-1-counter]
            counter++;
        }
    }
    return toReturn;
    }
    

我使用以下代码测试了上述内容:

public static void main(String[] args) {
    BigNum bn = new BigNum(1234567);        
    System.out.println(bn);
}

输出:1,234,567

相关问题