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 |
1.データを作る,2.データを閲覧する,3.終了>2 |
年を4桁で入力してください(0:quit)>2016 |
1.データを作る,2.データを閲覧する,3.終了>3 |
アプリケーションクラス
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) { |
08 | System.out.print( "1.データを作る,2.データを閲覧する,3.終了>" ); |
09 | int select=s.nextInt(); |
18 | System.out.println( "アプリケーションを終了します。" ); |
23 | private static void createData() { |
25 | System.out.print( "何年度のデータを作成しますか(0:quit)>" ); |
26 | int year = s.nextInt(); |
28 | Map<Integer, Integer> months = new TreeMap<>(); |
29 | for ( int i = 1 ; i <= 12 ; i++) { |
30 | int sales = r.nextInt( 1000 ); |
33 | data.put(year, months); |
36 | private static void browseData() { |
38 | System.out.println( "データがありません。" ); |
42 | System.out.println( "何年度のデータを閲覧しますか" ); |
43 | for ( int year : data.keySet()){ |
44 | System.out.println(year); |
46 | System.out.print( "年を4桁で入力してください(0:quit)>" ); |
48 | if (!data.containsKey(year)){ |
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); |
コメント