Ben Ben - 2 months ago 11
Java Question

Trying to create hashmap and print out it's contents (keys)

I have a text file that I'm reading from and I'm trying to use the words in the text as file as keys in a hashmap. I then want to print the hashmap to see it's contents. This is a prelude to a larger project. I know I could simply print out the text file, but I'm trying to experiment with the hashmap data structure.
Here's the code I have so far:

import java.io.*; //needed for File class below
import java.util.*; //needed for Scanner class below

public class readIn {

public static void readInWords(String fileName){
try{
//open up the file
Scanner input = new Scanner(new File(fileName));
HashMap hm = new HashMap();
while(input.hasNext()){
//read in 1 word at a time and increment our count
String x = input.next();
System.out.println(x);
hm.put(x);
}
System.out.println(hm);
}catch(Exception e){
System.out.println("Something went really wrong...");
}
}


public static void main(String args[]){
int x = 10; //can read in from user or simply set here

String fileName = "test.txt";
readInWords(fileName);
}
}


When I run, I get a "no suitable method found for put(string)" error. My larger goal is to create this hash map and store a list of places where a certain keys appears as a value. However right now I'm just trying to learn more about hashmaps through practice and wanted to see if anyone knows why this doesn't work.

Answer

There are no .put(x) method in Map iterface. You must use put() method with key argument. In your situation do it like this: hm.put(x, x);