Am having a problem accessing the data in a HashMap. It was created in one class and is being called from another. See below;
Created
public class LoadDatabase {
public Map virusDatabase = new HashMap();
...
public void toHash(String v_Name, String signature) {
virusDatabase.put(v_Name, signature);
}
...
public void printDatabase() { // This method is displaying correct data, so is being stored.
Iterator iterator = virusDatabase.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println(key + " = " + virusDatabase.get(key));
}
}
...
}
Need Access
public class LCS {
LoadDatabase lb = new LoadDatabase();
Tokenizer T = new Tokenizer();
...
public void buildDataLCS(String[] inTokens) {
Iterator iterator = lb.virusDatabase.keySet().iterator();
...
while (iterator.hasNext()){
String key = (String) iterator.next();
String v_sig = (String) lb.virusDatabase.get(key);
System.out.println(v_sig); //Example of problem, nothing printed
...
}
...
}
Why is the problem happening? Could you point me in the right direction.
Either of the 2 issues,
You are not putting anything there. As I can't see your invocation of toHash(String v_Name, String signature) method.
You are using 2 different instances of LoadDatabase class, somehow. Try making LoadDatabase singleton.
Carlos
I suspect you are not putting what you think you are putting into the map, or the keys when you put data in are not the same as when you take values out. I would log/print the key/val you put in, and then log/print the key/val you try to get out.
Related
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 3 months ago.
English is not my first language. Sorry in advance if there's something unclear.
I'm working on a college assignment using Enum and Google Guava Multimap. In my previous assignment(which is almost the same as the one I'm working on), I wrote down a bunch of words. Word for key, and definition for value. I used a scanner to type in the string value and check if there was anything matched in the enum. In the current assignment, I have to add 'part of the speech'. But, I'm not sure what/how to do that.
public class Test1
{
private enum Entry
{
BOOK("Book","noun", "A written work published in printed or electric form."),
BOOK2("Book","verb","To arrange for someone to have a seat on a plane."),
BOOKABLE("Bookable","adjective","Can be ordered in advance."),
BOOKCASE("Bookcase","noun","A piece of furniture with shelves."),
BOOKBINDER("Bol okBinder","noun","A person who fastens the pages of books."),
CSC2201("CSC220","noun","Data Structures."),
CSC2202("CSC220","adjective","Ready to create complex data structures."),
CSC2203("CSC220","verb","To create data structures.");
private String key;
private String partOfSpeech;
private String definition;
private Entry() {}
Entry(String key, String partOfSpeech, String definition)
{
this.key = key;
this.partOfSpeech = partOfSpeech;
this.definition = definition;
}
public String getKey()
{
return this.key.toUpperCase();
}
public String getPartOfSpeech()
{
return this.partOfSpeech;
}
public String getDefinition()
{
return this.definition;
}
public String toString()
{
return this.key+" ["+ this.partOfSpeech+"] : "+this.definition;
}
}
public static void main(String[]args)
{
ListMultimap<String, String> dictionary = ArrayListMultimap.create();
dictionary.put(Entry.BOOK.getKey(),Entry.BOOK.getDefinition());
dictionary.put(Entry.BOOK2.getKey(), Entry.BOOK2.getDefinition());
dictionary.put(Entry.BOOKABLE.getKey(), Entry.BOOKABLE.getDefinition());
dictionary.put(Entry.BOOKCASE.getKey(), Entry.BOOKCASE.getDefinition());
dictionary.put(Entry.BOOKBINDER.getKey(), Entry.BOOKBINDER.getDefinition());
dictionary.put(Entry.CSC2201.getKey(), Entry.CSC2201.getDefinition());
dictionary.put(Entry.CSC2202.getKey(), Entry.CSC2202.getDefinition());
dictionary.put(Entry.CSC2203.getKey(), Entry.CSC2203.getDefinition());
ListMultimap<String,String> partOfSpeechDict = ArrayListMultimap.create();
partOfSpeechDict.put(Entry.BOOK.getKey(),Entry.BOOK.getPartOfSpeech());
partOfSpeechDict.put(Entry.BOOK2.getKey(), Entry.BOOK2.getPartOfSpeech());
partOfSpeechDict.put(Entry.BOOKABLE.getKey(), Entry.BOOKABLE.getPartOfSpeech());
partOfSpeechDict.put(Entry.BOOKCASE.getKey(), Entry.BOOKCASE.getPartOfSpeech());
partOfSpeechDict.put(Entry.BOOKBINDER.getKey(),Entry.BOOKBINDER.getPartOfSpeech());
partOfSpeechDict.put(Entry.CSC2201.getKey(), Entry.CSC2201.getPartOfSpeech());
partOfSpeechDict.put(Entry.CSC2202.getKey(), Entry.CSC2202.getPartOfSpeech());
partOfSpeechDict.put(Entry.CSC2203.getKey(), Entry.CSC2203.getPartOfSpeech());
System.out.println("- DICTIONARY JAVA Standard -----");
System.out.println("----- powered by Google Guava -");
String searchKey = "null";
String endCode = "!q";
do
{
Scanner scan = new Scanner(System.in);
System.out.print("Search: ");
searchKey = scan.nextLine();
searchKey = searchKey.toUpperCase();
if(dictionary.containsKey(searchKey))
{
char[]charArray = searchKey.toCharArray();
for(int i=1;i<charArray.length;i++)
charArray[i]=Character.toLowerCase(charArray[i]);
String str = new String(charArray);
System.out.println(" |");
iterate(dictionary,str);
System.out.println(" |");
}
else if(searchKey.equalsIgnoreCase(endCode))
{
break;
}
else
{
System.out.println(" |");;
System.out.println("\t<Not found>");
System.out.println(" |");
}
}while(!searchKey.equalsIgnoreCase(endCode));
System.out.println("\n-----THANK YOU-----");
}
public static <K,V> void iterate(ListMultimap<String, String> alMultimap,String str)
{
for(Map.Entry<String,String> entry : alMultimap.entries())
{
if(str.equalsIgnoreCase(entry.getKey()))
{
char[]charArray = entry.getKey().toCharArray();
for(int i=1;i<charArray.length;i++)
charArray[i]=Character.toLowerCase(charArray[i]);
String str2 = new String(charArray);
System.out.print("\t"+str2+" ["+getPartOfSpeech(partOfSpeechDict, str2)+"] : "+entry.getValue()+"\n");
//IDE said that error is java : cannot find symbol(partOfSpeechDict). However, I made it.
}
}
}
public static <K,V> String getPartOfSpeech(ListMultimap<String, String> alMultimap,String str)
{
for(Map.Entry<String,String> entry : alMultimap.entries())
{
if(str.equalsIgnoreCase(entry.getKey()))
{
return entry.getValue();
}
}
return null;
}
}
To handle the problem, I made two ListMutimap<String, String> name = ArrayListMultimap.create(). Both of their keys are words, but the first map's value is a definition, and the second map's value is part-of-speech. I'm trying to use the method 'getPartOfSpeech' to get only the value(partOfSpeech) from the second map. Then add that value into the printing line in 'iterate', so it will print out the name, partOfSpeech, and definition. However, IDE said it can't find a symbol: "partOfSpeechDict".
What did I do wrong? Can I not make two maps using Guava Multimap? Please let me know.
Thank you.
I also uploaded about error message, but stackOverflow said there's a related question and decreased my reputation, so I deleted it TT :(
You declare your partOfSpeechDict in main method and then call it in iterate method, which is not able to because of the variable scope inside a method. you can not create a variable in this method and then use it in another method out of nothing like that
If you want to use the partOfSpeechDict map in your iterate method, add it to the parameters just like you did it with the dictionary map
public static void iterate(ListMultimap<String, String> alMultimap,
ListMultimap<String,String> partOfSpeechDict, // include your map here to use it
String str) {
for(Map.Entry<String,String> entry : alMultimap.entries()) {
if(str.equalsIgnoreCase(entry.getKey())) {
char[]charArray = entry.getKey().toCharArray();
for(int i=1;i<charArray.length;i++)
charArray[i]=Character.toLowerCase(charArray[i]);
String str2 = new String(charArray);
System.out.print("\t"+str2+" ["+getPartOfSpeech(partOfSpeechDict, str2)+"] : "+entry.getValue()+"\n");
}
}
}
So, this returns me
java.util.ConcurrentModificationException
and points to System.out.println line
Iterator<Autor> it = autores.iterator();
// Declaring a class iterator
public void listarAutores() {
while (it.hasNext()) {
String aux = it.next().getNomeCompleto();
// Get string from Class Autor method
System.out.println(aux);
// Printing that string
}
}
Why it's happening and how can i fix it?
This can happen if you modify the collection between two calls to the method. For example:
listarAutores();
autores.add(anotherAuthor);
listarAutores();
You should create a new iterator in the method at every call or, even better, not use an iterator at all:
public void listarAutores() {
for (Author a : autores) {
String aux = a.getNomeCompleto();
// Get string from Class Autor method
System.out.println(aux);
// Printing that string
}
}
Move your Iterator into the method call. You probably modify the Set somewhere in between.
I don't know if this is possible in Java but I was wondering if it is possible to use an object in Java to return multiple values without using a class.
Normally when I want to do this in Java I would use the following
public class myScript {
public static void main(String[] args) {
// initialize object class
cl_Object lo_Object = new cl_Object(0, null);
// populate object with data
lo_Object = lo_Object.create(1, "test01");
System.out.println(lo_Object.cl_idno + " - " + lo_Object.cl_desc);
//
// code to utilize data here
//
// populate object with different data
lo_Object = lo_Object.create(2, "test02");
System.out.println(lo_Object.cl_idno + " - " + lo_Object.cl_desc);
//
// code to utilize data here
//
}
}
// the way I would like to use (even though it's terrible)
class cl_Object {
int cl_idno = 0;
String cl_desc = null;
String cl_var01 = null;
String cl_var02 = null;
public cl_Object(int lv_idno, String lv_desc) {
cl_idno = lv_idno;
cl_desc = lv_desc;
cl_var01 = "var 01";
cl_var02 = "var 02";
}
public cl_Object create(int lv_idno, String lv_desc) {
cl_Object lo_Object = new cl_Object(lv_idno, lv_desc);
return lo_Object;
}
}
// the way I don't really like using because they get terribly long
class Example {
int idno = 0;
String desc = null;
String var01 = null;
String var02 = null;
public void set(int idno, String desc) {
this.idno = idno;
this.desc = desc;
var01 = "var 01";
var02 = "var 02";
}
public int idno() {
return idno;
}
public String desc() {
return desc;
}
public String var01() {
return var01;
}
public String var02() {
return var02;
}
}
Which seems like a lot of work considering in Javascript (I know they are different) I can achieve the same effect just doing
var lo_Object = f_Object();
console.log(lo_Object["idno"] + " - " + lo_Object[desc]);
function f_Object() {
var lo_Object = {};
lo_Object = {};
lo_Object["idno"] = 1;
lo_Object["desc"] = "test01";
return lo_Object;
}
NOTE
I know the naming convention is wrong but it is intentional because I have an informix-4gl program that runs with this program so the coding standards are from the company I work for
The best way to do this is to use HashMap<String, Object>
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Object> person =
new HashMap<String, Object>();
// add elements dynamically
person.put("name", "Lem");
person.put("age", 46);
person.put("gender", 'M');
// prints the name value
System.out.println(person.get("name"));
// asures that age element is of integer type before
// printing
System.out.println((int)person.get("age"));
// prints the gender value
System.out.println(person.get("gender"));
// prints the person object {gender=M, name=Lem, age=46}
System.out.println(person);
}
}
The advantage of doing this is that you can add elements as you go.
The downside of this is that you will lose type safety like in the case of the age. Making sure that age is always an integer has a cost. So to avoid this cost just use a class.
No, there is no such a feature, you have to type out the full type name(class name).
Or use may use val :
https://projectlombok.org/features/val.html
Also, if you use IntelliJ IDEA
try this plugin :
https://bitbucket.org/balpha/varsity/wiki/Home
I am not sure if it's possible with Java. Class is the primitive structure to generate Object. We need a Class to generate object. So, for the above code, i don't think there is a solution.
Java methods only allow one return value. If you want to return multiple objects/values consider returning one of the collections. Map, List, Queue, etc.
The one you choose will depend on your needs. For example, if you want to store your values as key-value pairs use a Map. If you just want to store values sequentially, use a list.
An example with a list:
list<Object> myList = new ArrayList<Object>();
myList.add("Some value");
return myList;
As a side note, your method create is redundant. You should use getters and setters to populate the object, or populate it through the constructor.
cl_Object lo_Object = new cl_Object(1, "test01");
The way you have it set up right now, you're creating one object to create another of the same type that has the values you want.
Your naming convention is also wrong. Please refer to Java standard naming convention:
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367
this is what i have so far and what im trying to do i dont know how to access both parts of the split this code is really wrong but i dont know how to do what i want(yes it is for school)
public class Relatives
{
private Map<String,Set<String>> map;
/**
* Constructs a relatives object with an empty map
*/
public Relatives()
{
map = new TreeMap<String,Set<String>>();
}
/**
* adds a relationship to the map by either adding a relative to the
* set of an existing key, or creating a new key within the map
* #param line a string containing the key person and their relative
*/
public void setPersonRelative(String line)
{
String[] personRelative = line.split(" ");
if(map.containsKey(personRelative[0]))
{
map.put(personRelative[0],map.get(personRelative[1])+personRelative[1]);
}
else
{
map.put(personRelative[0],personRelative[1]);
}
}
im trying to access the person and add to there current relatives and if the dont exist create a new person with that relative
how would i format it so it returns like this
Dot is related to Chuck Fred Jason Tom
Elton is related to Linh
i have this but get error
public String getRelatives(String person)
{
return map.keySet();
}
You cannot add an item to a Set using the += operator; you must use the add method.
Also, you have to create the set the first time you are going to use it.
The fixed code could look like:
String[] personRelative = line.split(" ");
String person = personRelative[0];
String relative = personRelative[1];
if(map.containsKey(person))
{
map.get(person).add(relative);
}
else
{
Set<String> relatives = new HashSet<String>();
relatives.add(relative);
map.put(person,relatives);
}
I don't think i have the terminology correct, haven't been one for that. What i'm trying to do is get a string back , then use it to run functions. .. Example :
int slotNumber = ((j*3)+i+1);
String slotString = "slot"+slotNumber;
Regularly I can do this :
slot12.Draw();
And I want to be able to do this :
slotString.Draw();
With it substituting slotString with slot12 in a dynamic scenario. If i truly have to i could do something similar to :
if (slotString == slot1) slot1.Draw();
if (slotString == slot2) slot2.Draw();
And such, but i dont really want to use x number of lines for x number of slots.
Any help is appreciated :D
A possible solution would be to use a HashMap where the key is the slotNumber and the value points to the slot. Then you could do something like the following.
//Initialize at the start of your program
HashMap<int, Slot> SlotHash = new HashMap<int, Slot>();
//Code to retrieve slot and call Draw().
Slot select = SlotHash.get(slotNumber);
select.Draw();
Maybe use a Map if your slots are sparsely-packed. If they're densely-packed, you might be able to use an array of slots. In either case, you do the slot lookup based on index and then call Draw on the looked-up slot.
You would have something like this:
Slot slot1 = new Slot("slot1");
Slot slot2 = new Slot("slot2");
SlotController controller = new SlotController();
controller.add(slot1);controller.add(slot2);
String someSlotNumber = ".....";
controller.draw(someSlotNumber);
See the definition of the classes below:
class SlotController {
Map<String, Slot> slotMap = new HashMap<String, Slot>();
public void addSlot(Slot aSlot) {
slotMap.put(aSlot.getSlotName(), aSlot);
}
public void draw(String slotName) {
slotMap.get(slotName).draw();
}
}
class Slot {
private String slotName;
public Slot(String name){
slotName = name;
}
public String getSlotName() {
return slotName;
}
public void draw() {
}
}