前提・実現したいこと
javaで"red green blue blue green blue "が入力されたとき、
単語がカウントされるコードを描いています。
単語の数をHashMapの値に格納してカウントしたいのですが
上手くいきません
例えば
"red green blue blue green blue "が入力されたときに
red 1
green 2
blue 3
となるようにしたいです。
発生している問題・エラーメッセージ
HashMapの中身が{red green blue blue green blue=1}となってしまっているのですが 何故こうなっているのかわかりません
該当のソースコード
java
1import java.util.*; 2 3 4public class Main { 5 public static void main(String[] args) { 6 // 自分の得意な言語で 7 // Let's チャレンジ!! 8 HashMap<String ,Integer> HM = new HashMap<String ,Integer>();//キーKey,値Value 9 Scanner sc = new Scanner(System.in); 10 11 //--この間をループさせたい-------------------------------------- 12 13 boolean Scanner_Next = true ; 14 15 Integer V = 0; 16 17 try{ 18 while(Scanner_Next == true){ 19 20 21 22 //-----この間がおかしい?--------------------------------------- 23 24 String line = sc.nextLine();//"red green blue blue green blue " が入力されて、1週目は"red "が取得される 25 26 27 if(HM.containsKey(line)){//HashMapにnextLineで読み取られたキー上がるとき、対応する値を取得し+1して格納 28 V = HM.get(line) ;// HM.get(line)はkeylineに対応する値valueを取得するメソッド 29 V = ++V ;//valueを+1する 30 HM.put(line,V);//+1された値をキーと一緒に上書き格納 31 }else{ 32 HM.put(line,1);//HashMapにnextlineで読み取られたキーがないとき、そのキーと値1を格納 33 } 34 35 //-------------------------------------------- 36 37 38 39 }//while 40 }catch(NoSuchElementException e){ 41 Scanner_Next = false;//スキャナーに次のトークンがない時、falseを代入してループ終了 42 } 43 44 //-------------------------------------------- 45 46 47 48 49 for(String k : HM.keySet()){ 50 Integer v = HM.get(k); 51 System.out.println(k+" "+v); 52 } 53 54 55 } 56}
試したこと
たしか 「paiza 転職」の問題ですよねこれ
回答1件
あなたの回答
tips
プレビュー