2016-11-29 11 views
3

私はHashMapsを初めて使用しています。私は追加することができるかどうか、ユーザーに尋ねることができるかどうか疑問に思っていましたか?これまではHashMapを印刷していましたが、何らかの理由でビューを要求するときにnullを返し、キーを削除しようとしたときにもキーを削除しません。どのように要素をハッシュマップに追加しますか?

import java.util.Scanner; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.Map; 
import java.util.Set; 

public class HashMapDemo { 
    public static void main (String [] args){ 
    //declaring a hashmap 
    HashMap<Integer, String> hm = new HashMap<Integer, String>(); 

    //adding elements to the hashmap 
    hm.put(1, "Josh"); 
    hm.put(2, "Max"); 
    hm.put(3, "Karan"); 

    //declaring the Scanner 
    Scanner sc = new Scanner(System.in); 
    System.out.println("Would you like to add Elements to the hashmap?"); 
    String scYN = sc.nextLine(); 
    scYN = scYN.toLowerCase(); 
    if(scYN.equals("yes")) { 
     System.out.println("What would the key to be?"); 
     int key = sc.nextInt(); 
     sc.nextLine(); 
     System.out.println("What would the value to be?"); 
     String val = sc.nextLine(); 
     hm.put(key, val);   
    }else if (scYN.equals("no")) { 
     System.out.println("False"); 
    }else{ 
     System.out.println("False"); 
    } 

    //displaying content 
    Set set = hm.entrySet(); 
    Iterator iterator = set.iterator(); 
    while(iterator.hasNext()){ 
     Map.Entry mentry = (Map.Entry)iterator.next(); 
     System.out.print("Key is: "+ mentry.getKey() + " & Value is: "); 
     System.out.println(mentry.getValue()); 
    } 

    /* Get values based on key*/ 

    System.out.println("What value would you like to find?"); 
    String fVal = sc.nextLine();   
    String var= hm.get(fVal); 
    System.out.println("Value at index " + fVal + " is: "+ var); 

    /* Remove values based on key*/ 

    System.out.println("Would you like to remove a key?"); 
    String remKey = sc.nextLine(); 
    hm.remove(remKey); 
    System.out.println("Map key and values after removal:"); 
    Set set2 = hm.entrySet(); 
    Iterator iterator2 = set2.iterator(); 
    while(iterator2.hasNext()) { 
     Map.Entry mentry2 = (Map.Entry)iterator2.next(); 
     System.out.print("Key is: "+mentry2.getKey() + " & Value is: "); 
     System.out.println(mentry2.getValue()); 
    } 

} 

}

あなたはのget()を使用する場合、キーがparamanter(FVAL)として渡されるので、それはあなたにNULL値を与えるお時間を

+3

あなたは '整数 'キーを保存していて、' String'キーを取得しようとしています。 – shmosel

+1

マップキーは 'Integer'なので、' String'に 'get()'を使ってみると失敗することがあります。 (文字列があなたが望む整数のように見えても、Javaは自動的に整数に変換されません。あなたはそれを自分で行う必要があります。) – ajb

+1

簡単な修正は、 、 "foo") ' – Bohemian

答えて

2

をありがとうですa 文字列ですが、ハッシュマップでは整数と定義されています。この問題を解決するために

、FVAL変数はnextIntを(取得整数ことがあります)

int fVal = sc.nextInt(); 

キーは何をするだろう」と、データ・エントリを勧誘するときは、これをしませんでしたか? "検索基準のプロンプトを表示するときに、「どのような価値を見つけたいでしょうか?」というプロンプトが表示され、削除のプロンプトが表示されたときに「キーを削除しますか?」と表示されます。

関連する問題