【问题标题】:Creating a toString method that returns an array in java在java中创建一个返回数组的toString方法
【发布时间】:2018-12-23 20:08:49
【问题描述】:

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

从数字的右侧开始每 3 位数字后,它应该 添加逗号,但如果数字的位数为 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;
    }

【问题讨论】:

  • 我不确定您所说的“返回数组的 toString 方法”是什么意思,因为代码中的 toString 不返回数组。
  • 该方法应该返回一个字符串,该字符串打印出现在数组中的数字,如上所述。对不起我的语言不好。
  • 删除此行this.num = new int[MAX_DIGITS];
  • 我试过了,但没用
  • 你的主要功能在哪里。

标签: java arrays tostring


【解决方案1】:

您可以尝试以下代码。请记住复制 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

【讨论】:

  • 数字应该是数组类型
  • 我没明白你的意思。你指的是输入new BigNum(1234567)吗?我没有更改num 的类型。它仍然是 int 数组。这就是为什么我能够做到this.num.length
  • 不,对不起,我的意思是这个 int number = (int)n;我被要求在开始时将其设为数组类型
  • 其实我已经从上面发布的问题中获取了这行代码。您能否编辑问题以使其更清楚?
  • 构造函数对我来说不是很清楚(关于这个问题,而不是你的答案;))。
猜你喜欢
  • 1970-01-01
  • 2017-01-02
  • 2016-04-05
  • 1970-01-01
  • 2018-12-16
  • 2020-11-02
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多