最终:库存台账
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 多文件 API 中。它实现了相同的有效行约定;所有中间总数都能放入 Java int。
using System;
using System.Collections.Generic;
using System.Globalization;
class Program {
static string Summarize(IEnumerable<string> rows) {
var totals = new SortedDictionary<string,int>(StringComparer.Ordinal);
foreach (string row in rows) {
string[] parts = row.Split(' ');
int previous;
totals.TryGetValue(parts[0], out previous);
totals[parts[0]] = previous + Int32.Parse(parts[1], CultureInfo.InvariantCulture);
}
var result = new List<string>();
foreach (var entry in totals)
if (entry.Value > 0) result.Add(entry.Key + ":" + entry.Value);
return result.Count == 0 ? "empty" : String.Join("\n", result);
}
static void Main() {
var rows = new List<string>();
string line;
while ((line = Console.ReadLine()) != null) rows.Add(line);
Console.WriteLine(Summarize(rows));
}
}亲手试试
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 在线编译器