マップと存在しないキー
Coddyの「C開発者のためのJava」コースのレッスン 14/48。
標準Cには、文字列キーを扱う汎用マップが用意されていません。検索と挿入は、テーブルまたはライブラリで定義する必要があります。JavaのMap.getは、存在しないキーを挿入せず、nullを返すことがあるため、アンボクシングは安全ではありません。containsKeyまたは適切なフォールバックを使い、HashMapが挿入順を保持すると想定するのではなく、キーを自然順で並べるにはTreeMapを選びましょう。
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <ctype.h>
int main(void) {
struct Entry {const char *name;int total;}; struct Entry entries[]={{"free",0}}; int total=-1; bool found=false; for(size_t i=0;i<1;i++) if(strcmp(entries[i].name,"free")==0) {total=entries[i].total;found=true;} printf("%d %s\n",total,found?"true":"false");
return 0;
}
Java
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Example {
public static void main(String[] args) {
Map<String,Integer>counts=new HashMap<>();counts.put("red",counts.getOrDefault("red",0)+1);System.out.println(counts.get("red"));
}
}
各例では言語ごとの動作を切り分けており、異なる値を使っている場合があります。それぞれを個別に追ってください。期待される出力が一致するとは限りません。Javaの課題では、編集可能なクラスを通じて、新しい入力に同じ概念を適用します。
チャレンジ
簡単入力は、空白で区切られた小文字の単語が並ぶ1行です。各単語の出現回数を数え、アルファベット順に並べたword:countの項目を別々の行で返してください。入力が空の場合は、空を返します。
末尾に改行を付けず、正確な結果テキストをExercise.solve(List<String> input)から返してください。画面に表示されるロック済みのMain.javaは、入力のすべての行を読み込み、返されたテキストを最後に改行を1つ付けて出力します。編集可能なメソッド内で出力してはいけません。特に明記されていない限り、すべての整数と算術結果はJavaのintに収まります。
編集可能なファイル:Exercise.java、Text.java。Text.javaには、再利用可能な解析および書式設定用のヘルパーが用意されています。すべてのファイルは名前なしパッケージに属し、一緒にコンパイルされます。Main.javaが唯一のエントリーポイントであり、編集できません。
自分で試してみよう
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オンラインコンパイラ