[英]Do-While Loop goes infinite
I have an abstract class that contains a variable of type String declared moneyString 我有一个抽象类,其中包含一个声明为moneyString的 String类型的变量
String moneyString;
It contains data something like $123,456,789 它包含的数据类似$ 123,456,789
So inside the abstract class I have function 所以在抽象类中我有功能
void convertToInt(){
remove(',');
remove('$');
empMoney = Integer.parseInt(moneyString.substring(0, moneyString.length()) );
}
And my remove function 和我的删除功能
void remove(char character){
boolean moreFound = true;
String tempString;
int index;
do{
index = moneyString.indexOf(character);
tempString = moneyString;
if(index!=-1){
//From beggining to the character
moneyString = moneyString.substring(0,index);
//After the character to the end
tempString = tempString.substring(index,tempString.length());
moneyString += tempString;
}
else{
moreFound = false;
}
} while(moreFound);
} //END remove()
Isn't it supposed to get out of the loop when when moreFound = false? 当moreFound = false时,它是否应该退出循环?
The issue with your code is here, 您的代码存在问题,
tempString = tempString.substring(index,tempString.length());
Should be index + 1
because you don't want to include that character. 应该是
index + 1
,因为你不希望包括字符。
tempString = tempString.substring(index + 1,tempString.length());
But, I suggest you use a DecimalFormat
and parse(String)
the value. 但是,我建议您使用
DecimalFormat
并parse(String)
值。 Like, 喜欢,
public static int convertToInt(String money) throws ParseException {
NumberFormat df = new DecimalFormat("$#,###");
return df.parse(money).intValue();
}
Then you can call it like 然后你可以这样称呼它
public static void main(String[] args) {
try {
System.out.println(convertToInt("$123,456,789"));
} catch (ParseException e) {
e.printStackTrace();
}
}
Output is 输出是
123456789
Indeed you have to change the line: 实际上,您必须更改这一行:
tempString = tempString.substring(index,tempString.length());
to: 至:
tempString = tempString.substring(index+1,tempString.length());
The assignment could be done to a variable of type Long: 可以对Long类型的变量进行赋值:
moneyString="$123,456,789,101";
long empMoney;
remove('$');
remove(',');
empMoney = Long.parseLong(moneyString.substring(0, moneyString.length()) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.