使用substring java分隔数字

问题描述 投票:-2回答:2

我想用Java创建一个程序,从user_input获取数字并使其成为货币格式......这是我的代码

package Seperator_checker;

import java.util.Scanner;

public class Seperator {

    public static void main(String[] args) {
        Scanner number=new Scanner(System.in);
        System.out.print("Please Enter Your Number: ");
        String user_number=number.next();
        if(user_number.length()> 3) {
            user_number=user_number.substring(0,user_number.length()-3) + "," + user_number.substring(0,1);
            System.out.println("________________________________________");
            System.out.println("Your Currency Number Is: "+ user_number);
        }

    }

}
java web substring
2个回答
0
投票

我能想到的一个自发的答案是将字符串拆分为Chars列表,然后向后遍历并在每第三步后插入一个,,直到你到达开头。

伪代码:

Convert String to Char List
goto end of List
counter = 0
while havent reached beginning of list
    counter += 1
    if counter == 3
        counter = 0
        insert ',' into List
        //maybe go back one here too depending on implementation of 
        //insert and which is the current element after inserting
    end if
    go one back one element in List
end while

对不起,我不知道如何编写伪代码


0
投票

如果你必须使用substring:

我不知道如何把它写成文字,所以这里是代码:)

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        int rest = input.length() % 3;
        if(rest == 0){
            rest = 3;
        }
        //add the "irregular" comma
        input = input.substring(0,rest) + "," + input.substring(rest);

        //add the rest
        for(int i = rest+1;i < input.length()-3; i+= 4){//4 because of the comma
            input = input.substring(0, i+3) + "," + input.substring(i+3, input.length()); 
        }
        System.out.println(input);
    }
}

(基本上首先在开头处理不规则部分,然后按步骤3(4,因为你插入逗号)并插入逗号)

希望这可以帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.