要创建家庭预算,你需要找出你的净收入,也就是你的收入减去你的支出。 编写一个Java方法,接受一个输入字符串并计算收入减去费用。

img


要创建家庭预算,你需要找出你的净收入,也就是你的收入减去你的支出。

编写一个Java方法,接受一个输入字符串并计算收入减去费用。

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            calcNetIncome(s);
        }
    }
 
    private static void calcNetIncome(String s) {
        Pattern compile = Pattern.compile("[-]?[0-9]+");
        Matcher matcher = compile.matcher(s);
        List<Integer> data = new ArrayList<>();
        while (matcher.find()) {
            data.add(Integer.parseInt(matcher.group()));
        }
        Integer sum = 0;
        for (Integer item : data) {
            sum += item;
        }
        System.out.println(String.format("calcNetIncome(\"%s\") → %s", s, sum));
    }
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632