簡體   English   中英

如何獲取用戶輸入並將其存儲到HashMap中並分別創建兩個鍵以進行打印?

[英]How do I get user input and store it into a HashMap and create the two keys separately to print out?

我剛剛開始學習HashMaps,可以將它們打印出來,但是我在弄清楚如何獲取兩個值的userInput時將它們存儲然后打印出來時遇到了麻煩。

還是我以錯誤的方式看待這個問題?

System.out.println("Let us know about your pets!");     
Map<String, String> pets = new HashMap<>();

String userInput; 
String name;
String type;        
int numberOfPets = 0; 
boolean valid = true; 

try (Scanner scnr = new Scanner(System.in)) {
   do { 
      System.out.println("Enter a name: ");
      name = userInput.put(scnr.nextLine());

      System.out.println("What type of animal is " + (name));
      type = userInput.put(scnr.nextLine());

      System.out.println("Would you like to enter another? (y/n) ");

      numberOfPets++; 

    } while (scnr.next().equalsIgnoreCase("y"));

}

System.out.println("You entered" + number of pets +"pets.");
for (String key : pets.keySet()) {
    System.out.println(key + " is a " + pets.get(key));
}

我希望結果顯示為:

輸入名稱:{用戶輸入Eustance}

Eustance是哪種動物:

{用戶進入龍}

您想輸入另一只寵物嗎?

{是}輸入

名稱:{用戶輸入Reepicheep}

Reepicheep是什么類型的動物:

{用戶進入鼠標}

您想輸入另一只寵物嗎?

{沒有}

您輸入了2只寵物。

輸入寵物名稱之一(或鍵入END退出):{用戶輸入Reepicheep} Reepicheep是鼠標。

您需要更改代碼以將名稱和類型存儲在HashMap ,如下所示,以便稍后可以通過使用pets.get(...)進行檢索pets.get(...)

try (Scanner scnr = new Scanner(System.in)) {
    do {
        System.out.println("Enter a name: ");
        name = scnr.nextLine();

        System.out.println("What type of animal is " + (name));
        type = scnr.nextLine();

        // change made here 
        pets.put(name, type);

        System.out.println("Would you like to enter another? (y/n) ");

        numberOfPets++;

      // here as well coz scanner was skipping the input
    } while (scnr.nextLine().equalsIgnoreCase("y")); 

}

您具有“讀取”操作:

pets.get(key)

您只需要一個“寫”操作(在您的輸入循環中):

pets.put(key, value)

有關完整的信息,請查看Map的JavaDocs,例如:

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

使用Map可以做各種各樣的事情!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM