场景
测验问题,明天期末考试,这个问题对我来说毫无意义,请有人告诉我符合标准的代码段。我尝试的一切都失败了。我最大的问题是我不知道如何引用“this”。所以我不知道我做得是否正确,我的老师不会给我是或否的答案,我将在下面的代码中发布我的尝试,希望有人会纠正我的错误。我将永远欠你的债!
问题
Write a BigInt CLASS function int countDigits() that returns the number of significant digits in the BigInt object (i.e "this"). Assume we are using the string representation for the BigInt (leading zeros not removed) significant digits start with the left-most non-zero if BigInt has a value of 0 the number significant digits is 1`
我尝试过的
public int countDigits()
{
int i = 0;
while(this.number.charAt(i)=='0')//this.number will reference a string object
i++;
String str = this.number.substring(i,number.length();)//this.number will reference the string object
System.out.println("leading zeros removed : "+str);
System.out.println(" number of significant digits = "+str.length());
return str.length();
}
最佳答案
如果您有一个字段number
,则这两个表达式:
this.number
number
在您的代码中效果相同。当存在与字段同名的局部变量或参数时,您只需在字段名称前添加 this.
即可,从而遮蔽它。
虽然没有直接回答您的问题,但更值得思考,因为您有一个字符串来存储您的号码,请考虑对您的方法使用字符串方法:
public int countDigits() {
return number.replaceAll("^0+", "").length();
}
这个单行解决方案首先生成一个删除所有前导零的字符串,然后简单地使用它的长度。
关于java - 尝试引用 "this"来引用当前字符串对象。不确定我这样做是否正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019674/