本日の課題
問題: 商品名を入力し値段が出るシステムをHashMap用いて制作せよ
回答
package osakana;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class fish {
public static void main(String[] args)throws Exception {
System.out.println("商品を入力してください");
Scanner s=new Scanner(System.in);
String Fish=s.next();
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("サバ",250);
map.put("マグロ",400);
map.put("ブリ",350);
map.put("サケ",300);
System.out.println(map.get(Fish)+"円");
}
}
結果
商品を入力してください
マグロ
400円
本日の気付き: map.get()内に、Fishを入れることで、相方の数字が出てきます。
本日の学び: map.putで格納できるため検索ツールに使えそうです。