结课:C++ 账本
Coddy 面向 C++ 开发者的 Java 课程的第 47 课,共 48 课。
挑战
简单输入包含零行或多行 name quantity。名称由小写 ASCII 字母组成,数量为带符号整数。汇总每个名称对应的数量,丢弃总和小于或等于零的项,并按字母顺序返回 name:total 行;如果没有剩余项,则返回 empty。所有中间总和都能用 int 表示。
返回不带末尾换行符的精确结果文本,调用方式为 Exercise.solve(List<String> input)。可见且锁定的 Main.java 会读取所有输入行,并在打印返回文本时添加一个末尾换行符。不要在可编辑的方法中打印内容。除非另有说明,所有整数和算术结果都能用 Java int 表示。
可编辑文件:Exercise.java、Text.java。Text.java 提供可重复使用的解析和格式化辅助方法。所有文件都位于未命名的包中,并会一起编译。Main.java 是唯一入口点,不能编辑。
将以下 C++ 参考算法移植为所需的 Java 实现。保留汇总、按名称排序以及移除非正数总和的逻辑。配套源程序已使用相同的五个输入样例运行。
#include <iostream>
#include <string>
#include <map>
#include <sstream>
int main() {
std::map<std::string,int> totals;
std::string line;
while (std::getline(std::cin,line)) {
std::istringstream row(line);
std::string name; int quantity;
row >> name >> quantity;
totals[name] += quantity;
}
bool any=false;
for (const auto& [name,total] : totals) {
if (total>0) { std::cout << name << ':' << total << '\n'; any=true; }
}
if (!any) std::cout << "empty\n";
}
亲手试试
import java.io.*;
import java.util.*;
public class Main {
private static void check(boolean condition) {
if (!condition) throw new AssertionError("Required public API behavior failed");
}
public static void main(String[] args) throws Exception {
List<String> input = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = reader.readLine()) != null) input.add(line);
System.out.println(Exercise.solve(input));
}
}
面向 C++ 开发者的 Java中的所有课
自己练习: Java 在线编译器