Menu
CoddyTech

Final: GDScript Ledger

Lesson 47 of 48 in Coddy's Java for GDScript Developers course.

challenge icon

Challenge

Easy

Input is zero or more name quantity rows. Names are lowercase ASCII letters and quantities signed integers. Aggregate each name, discard totals at most zero, and return alphabetically sorted name:total lines; if none remain, return empty. All intermediate totals fit int.

Return the exact result text without a final newline from Exercise.solve(List<String> input). The visible locked Main.java reads all input lines and prints the returned text with one final newline. Do not print inside editable methods. All integers and arithmetic results fit Java int unless stated otherwise.

Editable files: Exercise.java, Text.java. Text.java supplies reusable parsing and formatting helpers. All files are in the unnamed package and compile together. Main.java is the only entry point and cannot be edited.

Port this complete GDScript reference program to the Java multi-file API. It reads the same valid input rows; GDScript uses 64-bit integers, but the task bounds fit Java int.

extends Node

func _ready() -> void:
    var totals: Dictionary = {}
    var whitespace: RegEx = RegEx.new()
    whitespace.compile(r"\s+")
    while true:
        var line: String = OS.read_string_from_stdin()
        if line.is_empty():
            break
        var row: String = line.strip_edges()
        if row.is_empty():
            continue
        var parts: PackedStringArray = whitespace.sub(row," ",true).split(" ",false)
        var item: String = parts[0]
        totals[item]=int(totals.get(item,0))+int(parts[1])
    var keys: Array = totals.keys()
    keys.sort()
    var result: PackedStringArray = []
    for key: String in keys:
        if int(totals[key])>0:
            result.append(key+":"+str(totals[key]))
    print("\n".join(result) if not result.is_empty() else "empty")

Try it yourself

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));
    }
}

All lessons in Java for GDScript Developers

Practice on your own: Online Java compiler