Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

java - Joining both hashsets together

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);

  }
}

errors exsist

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...