简体   繁体   中英

Do-While Loop goes infinite

I have an abstract class that contains a variable of type String declared moneyString

String moneyString;

It contains data something like $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?

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.

tempString = tempString.substring(index + 1,tempString.length());

But, I suggest you use a DecimalFormat and parse(String) the value. 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:

moneyString="$123,456,789,101";
long empMoney;
remove('$');
remove(',');
empMoney = Long.parseLong(moneyString.substring(0, moneyString.length()) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM