Map例題集。Mapは
Map<Integer,Map<Integer,Integer>>
のように入れ子にできる。それを利用して以下のアプリを作成せよ。
Q1
データを作るでは年数を入れると、1〜12月のデータが作成される。
その際、月々の値は0~999の値がランダムに入れられる。
データを閲覧するでは。登録されている年度が一覧され、年度を入力することでその年度のデータを一覧できる。
詳しくは実行例を参照のこと
[実行例] 1.データを作る,2.データを閲覧する,3.終了>1 何年度のデータを作成しますか(0:quit)>2015 何年度のデータを作成しますか(0:quit)>2016 何年度のデータを作成しますか(0:quit)>2017 何年度のデータを作成しますか(0:quit)>0 1.データを作る,2.データを閲覧する,3.終了>2 何年度のデータを閲覧しますか 2015 2016 2017 年を4桁で入力してください(0:quit)>2016 1月:526 2月:900 3月:835 4月:989 5月:198 6月:462 7月:717 8月:555 9月:808 10月:138 11月:953 12月:363 何年度のデータを閲覧しますか 2015 2016 2017 年を4桁で入力してください(0:quit)>0 1.データを作る,2.データを閲覧する,3.終了>3 アプリケーションを終了します。
アプリケーションクラス
import java.util.*;
public class Q {
public static Map<Integer, Map<Integer, Integer>> data = new TreeMap<>();
public static Scanner s = new Scanner(System.in);
public static Random r=new Random();
public static void main(String[] args) {
while (true) {
System.out.print("1.データを作る,2.データを閲覧する,3.終了>");
int select=s.nextInt();
switch(select){
case 1:
createData();
break;
case 2:
browseData();
break;
case 3:
System.out.println("アプリケーションを終了します。");
return;
}
}
}
private static void createData() {
while (true) {
System.out.print("何年度のデータを作成しますか(0:quit)>");
int year = s.nextInt();
if(year == 0) return;
Map<Integer, Integer> months = new TreeMap<>();
for (int i = 1; i <= 12; i++) {
int sales = r.nextInt(1000);
months.put(i, sales);
}
data.put(year, months);
}
}
private static void browseData() {
if(data.isEmpty()){
System.out.println("データがありません。");
return;
}
while(true){
System.out.println("何年度のデータを閲覧しますか");
for(int year : data.keySet()){
System.out.println(year);
}
System.out.print("年を4桁で入力してください(0:quit)>");
int year=s.nextInt();
if(!data.containsKey(year)){
return;
}
Map<Integer,Integer> months=data.get(year);
for(int key:months.keySet()){
int value=months.get(key);
System.out.println(key+"月:"+value);
}
}
}
}

コメント