簡體   English   中英

Do-While循環無限

[英]Do-While Loop goes infinite

我有一個抽象類,其中包含一個聲明為moneyString的 String類型的變量

String moneyString;

它包含的數據類似$ 123,456,789

所以在抽象類中我有功能

void convertToInt(){
    remove(',');
    remove('$');
    empMoney = Integer.parseInt(moneyString.substring(0, moneyString.length()) );
}

和我的刪除功能

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()

當moreFound = false時,它是否應該退出循環?

您的代碼存在問題,

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

應該是index + 1 ,因為你希望包括字符。

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

但是,我建議您使用DecimalFormatparse(String)值。 喜歡,

public static int convertToInt(String money) throws ParseException {
    NumberFormat df = new DecimalFormat("$#,###");
    return df.parse(money).intValue();
}

然后你可以這樣稱呼它

public static void main(String[] args) {
    try {
        System.out.println(convertToInt("$123,456,789"));
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

輸出是

123456789

實際上,您必須更改這一行:

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

至:

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

可以對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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM