Javaの学習を始めて37日くらいの人のための問題集

Java

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
アプリケーションを終了します。

アプリケーションクラス

01import java.util.*;
02public class Q {
03  public static Map<Integer, Map<Integer, Integer>> data = new TreeMap<>();
04  public static Scanner s = new Scanner(System.in);
05  public static Random r=new Random();
06  public static void main(String[] args) {
07    while (true) {
08      System.out.print("1.データを作る,2.データを閲覧する,3.終了>");
09      int select=s.nextInt();
10      switch(select){
11      case 1:
12        createData();
13        break;
14      case 2:
15        browseData();
16        break;
17      case 3:
18        System.out.println("アプリケーションを終了します。");
19        return;      
20      }
21    }
22  }
23  private static void createData() {
24    while (true) {
25      System.out.print("何年度のデータを作成しますか(0:quit)>");
26      int year = s.nextInt();
27      if(year == 0) return;
28      Map<Integer, Integer> months = new TreeMap<>();
29      for (int i = 1; i <= 12; i++) { 
30        int sales = r.nextInt(1000);
31        months.put(i, sales);
32      }
33      data.put(year, months);
34    }
35  }
36  private static void browseData() {
37    if(data.isEmpty()){
38      System.out.println("データがありません。");
39      return;
40    }
41    while(true){
42      System.out.println("何年度のデータを閲覧しますか");
43      for(int year : data.keySet()){
44        System.out.println(year);
45      }
46      System.out.print("年を4桁で入力してください(0:quit)>");
47      int year=s.nextInt();
48      if(!data.containsKey(year)){
49        return;
50      }
51      Map<Integer,Integer> months=data.get(year);
52      for(int key:months.keySet()){
53        int value=months.get(key);
54        System.out.println(key+"月:"+value);
55      }
56    }
57  }
58}

コメント

タイトルとURLをコピーしました