将两个哈希集合在一起 [英] Joining both hashsets together
本文介绍了将两个哈希集合在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目标是创建一个数据库,类似于我添加行星的代码,以及它们被发现的年份,一旦用户输入行星,它就会显示所有行星和它们被发现的年份,到目前为止,我已经创建了这个行星。 p>
My aim is to create a database like code where i add planets and the year they are found, and once the user inputs planets it shows all the planets and the year they are found, so far i have created this.
import java.util.HashSet;
import java.util.Scanner;
import java.lang.*;
public class sky {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
// HashSet declaration
HashSet < String > planet =
new HashSet < String > ();
// Adding elements to the HashSet
planet.add("planet A");
planet.add("planet B");
planet.add("planet C");
planet.add("planet D");
planet.add("planet E");
//Addition of duplicate elements will not show
planet.add("planet A");
System.out.println("enter the word");
String input = in .next();
int count = 0;
for (int i = 0; i < input.length(); i++)
{
if (sky.contains(input.HashSet(i))) count++;
}
System.out.println("the planets are");
System.out.println(count);
HashSet < String > date =
new HashSet < String > ();
// Adding elements to the HashSet
date.add("2001");
date.add("2002");
date.add("2003");
date.add("2004");
date.add("2005");
//Displaying HashSet elements
System.out.println(planet);
System.out.println(date);
}
}
错误exsist
推荐答案
你需要的不是一个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);
}
}
这篇关于将两个哈希集合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文