尝试引用 "this" 引用当前字符串对象。不确定我这样做是否正确
Trying to reference "this" referencing to a current string object. Not sure if I'm doing this right
场景
测验问题,明天期末考试,这个问题对我来说毫无意义,有人请告诉我符合标准的代码段。我尝试的一切都失败了。我最大的问题是我不知道如何引用 "this"。所以我不知道我是否做对了,我的老师不会给我一个是或否的答案,我将 post 我尝试下面的代码,希望有人能纠正我的错误。我会永远欠你的债!
问题
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.
前缀,因此 shadowing 它。
虽然没有直接回答您的问题,但更值得深思,因为您有一个字符串来存储您的号码,请考虑对您的方法使用字符串方法:
public int countDigits() {
return number.replaceAll("^0+", "").length();
}
这个单行解决方案首先生成一个删除了所有前导零的字符串,然后简单地使用它的长度。
场景
测验问题,明天期末考试,这个问题对我来说毫无意义,有人请告诉我符合标准的代码段。我尝试的一切都失败了。我最大的问题是我不知道如何引用 "this"。所以我不知道我是否做对了,我的老师不会给我一个是或否的答案,我将 post 我尝试下面的代码,希望有人能纠正我的错误。我会永远欠你的债!
问题
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.
前缀,因此 shadowing 它。
虽然没有直接回答您的问题,但更值得深思,因为您有一个字符串来存储您的号码,请考虑对您的方法使用字符串方法:
public int countDigits() {
return number.replaceAll("^0+", "").length();
}
这个单行解决方案首先生成一个删除了所有前导零的字符串,然后简单地使用它的长度。