且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将两个哈希集合在一起

更新时间:2023-11-04 07:55:40

你需要的不是一个HashSet,而是一个HashMap。看看下面的程序,并试着了解这里究竟发生了什么。我建议你在阅读之前阅读HashMap的工作方式。

What you need is not a HashSet but a HashMap. Take a look at the program below and try to understand what exactly is going on here. I'll suggest you read how HashMap works before reading this.

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

public class sky {

  private static Map<String, Integer> planetMap = new HashMap<String,Integer>();
  public static void main(String args[]) {
    populateDB();
    Scanner scanner = new Scanner(System.in);

    String planetName = scanner.nextLine();

    if(planetMap.get(planetName) != null) {
      System.out.println("The planet "+ planetName +" was found in "+ planetMap.get(planetName));
    }
    else {
      System.out.println("Invalid Planet Name");
    }

  }

  public static void populateDB() {


    planetMap.put("Earth", 1600);
    planetMap.put("Mars", 1500);
    planetMap.put("Jupiter", 1100);
    planetMap.put("Saturn", 1900);
    planetMap.put("Venus", 1300);
  }
}