HashMap : Find a Value from a Key from different class - java

first take a look of my code so far here:
main program
public static void main(String[] args) {
KamusService service = new KamusService();
IKamus idKeEn = new IDKeEN();
String artiBelajar = service.cariArtiKata("belajar",idKeEn);
String artiPintu = service.cariArtiKata("pintu",idKeEn);
System.out.println(artiBelajar);
System.out.println(artiPintu);
}
KamusService class
public class KamusService {
public String cariArtiKata(String cariArtiKata, IKamus n) {
return n.terjemahkan();
}
idKeEn class
public class IDKeEN extends IKamus {
Map<String,String> id2en = new HashMap<String,String>();
public IDKeEN() {
id2en.put("belajar","learning");
id2en.put("pintu","door");
}
#Override
public String terjemahkan() {
return id2en.get("pintu");
}
}
and IKamus class
public abstract class IKamus {
public abstract String terjemahkan();
}
i wonder how to put "belajar" from String artiBelajar to my HashMap inside IDKeEN class as a key so main program can print String artiBelajar
From above you can see that my program's output is "door" because inside IDKeEN class it override the output.
i just wanna know how to make this line work
String artiBelajar = service.cariArtiKata("belajar",idKeEn);
use "belajar" as a Key for my HashMap and idKeEn as the destination class to process the whole things.
Thanks.

Related

Using a for loop to run class methods from multiple class objects in Java

(for some context) My real world problem is that I have many Text objects that depending on conditions will need the method text.setText("sometext") to be executed. (Im creating a calendar that as the months change, so does the first day of the month, which in turn causes the dates (1,31) to change where they appear on the calendar interface i created .
My approach was to create Text objects, add them to a HashMap. Then, depending on where the first day of the month is, call the appropriate Text objects from the HashMap and run a method from within the Text class text.setText("sometext")
i haven't added the actual code, because 99% is irrelevant and would probably just confuse issues but this code should illustrate what I'm trying to achieve. `public class Test {
public static void main(String[] args) {
ExampleCLass object1 = new ExampleCLass("object1");
ExampleCLass object2 = new ExampleCLass("object2");
HashMap<Integer, Object> hashMap = new HashMap<>();
//if some condition has been met
for(Object object : hashMap){
object.printname();
}
}
}`
public class ExampleCLass {
private final String name;
public ExampleCLass(String name) {
this.name = name;
}
public void printName(){
System.out.println(this.name);
}
}
any tips on getting this to work, or suggestions of a different/better approach would be massively appreciated.
Getting your code, which didn't even compile, to work.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class HashMapTest {
public static void main(String[] args) {
new HashMapTest().test();
}
public void test() {
HashMap<Integer, ExampleClass> hashMap = new HashMap<>();
ExampleClass object1 = new ExampleClass("object1");
hashMap.put(1, object1);
ExampleClass object2 = new ExampleClass("object2");
hashMap.put(2, object2);
// if some condition has been met
Set<Integer> hashSet = hashMap.keySet();
Iterator<Integer> iter = hashSet.iterator();
while (iter.hasNext()) {
Integer key = iter.next();
ExampleClass ec = hashMap.get(key);
System.out.println(ec.printName());
}
}
public class ExampleClass {
private final String name;
public ExampleClass(String name) {
this.name = name;
}
public String printName() {
return this.name;
}
}
}

How to add to array in main?

I have created an array which I wanted to control from main. My code runs, but I don't know how to add integers to the array from the main class. Also as each ConcreteSubject has its own storage array, how would i change this to store them all in the same array?
public class ConcreteSubject extends AbstractSpy
{
private AbstractSpy[] spies = new AbstractSpy[10];
private int i = 0;
public void addSpy(AbstractSpy s) {
if (i < spies.length) {
spies[i] = s;
System.out.println("spy added at index " + i);
i++;
}
}
}
public class TestClass
{
public static void main(String[] args) {
ConcreteSubject cs = new ConcreteSubject();
AbstractSpy spies = new AbstractSpy() {
#Override
public void addSpy(AbstractSpy spies) {
}
};
cs.addSpy(cs);
spies.addSpy(spies);
}
}
It seems like your program logic is a little borked. This bit in particular doesn't make much sense:
***AbstractSpy spies = new AbstractSpy() {
#Override
public void addSpy(AbstractSpy spies) {
}
};
cs.addSpy(cs);
***spies.addSpy(spies);
What you're doing is creating TWO AbstractSpy instances, one named cs and one named spies. On that last line you're adding spies to itself! That doesn't help you at all.
Note that AbstractSpy is the most granular unit in your setup - it shouldn't have an addSpy() method and its own internal array, it should be the thing that's added to something else's array!
Here's the same code, but cleaned up a bit:
public abstract class AbstractSpy { }
public class ConcreteSpy extends AbstractSpy { }
public class ConcreteSubject {
private AbstractSpy[] spies = new AbstractSpy[10];
private int i = 0;
public void addSpy(AbstractSpy spy) {
if (i < spies.length)
{
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
}
public class TestClass {
public static void main(String[] args) {
ConcreteSubject cs = new ConcreteSubject();
AbstractSpy spy = new ConcreteSpy();
cs.addSpy(spy);
}
}
The big difference here is that ConcreteSpy is an implementation of AbstractSpy that you can add to your ConcreteSubject's array of spies. I think you might have been confused by Java's insistence that you can't create an instance of an abstract class on its own unless you supply an anonymous class that inherits from the abstract class.

How to set a value on a class using another class that is called/set in main class

I have 3 classes, say: ShareType, ShareTypesTrue and Main.
public class ShareType {
public String shareTypeName = "";
public String noOfShare = "";
public String parValue = "";
public void setShareTypeName(String shareTypeName) {
this.shareTypeName = shareTypeName;
}
public void setNoOfShare(String noOfShare) {
this.noOfShare = noOfShare;
}
public void setParValue(String parValue) {
this.parValue = parValue;
}
}
public class ShareTypesTrue {
public List<ShareType> shareType;
public void setShareType(List<ShareType> shareType) {
this.shareType = shareType;
}
}
public class Main {
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
sharetypetrue.add(shareTypeName);
}
Now my problem is i need to set shareTypeName to a value under the class ShareTypesTrue. Meaning i have to use ShareTypesTrue to call on the Sharetype class and set the shareTypeName.
Anyone has an idea?
NOTE: I cant change/add code in the first 2 classes except in main. i just need to find a way to get around this.
Thanks Alot
Please check below code for Main class.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]){
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
//Create object
ShareType shareType = new ShareType();
shareType.setShareTypeName("Original Name");
//Create list
List<ShareType> shareTypes=new ArrayList<ShareType>();
shareTypes.add(shareType);
//Attach it to share
sharetypetrue.setShareType(shareTypes);
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
//Editing it.
for(ShareType shareTypesMember:sharetypetrue.shareType){
shareTypesMember.shareTypeName = "Updated Name";
}
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
}
}
Use Sharetype class to set the shareTypeName
ShareType share = new ShareType();
share.setShareTypeName("name");
share.setNoOfShare("no");
share.setParValue("val");
List<ShareType> shareType = new ArrayList<ShareType>();
shareType.add(share);
use ShareTypesTrue to set Sharetype
ShareTypesTrue sharetrue = new ShareTypesTrue();
sharetrue.setShareType(shareType);//pass ShareType as list
If you want to set the 'name' in ShareType, what prevents you from doing the below:
class ShareTypeTrue_Extended extends ShareTypeTrue{
protected shareTypeName;
public ShareTypeTrue_Extended(String shareTypeName){this.shareTypeName=shareTypeName;}
public void setShareType(List<ShareType> shareType) {
for(ShareType s: shareType)s.setShareTypeName(this.shareTypeName);
super.setShareType(shareType);
}
}

How do I use value from one class for another class Calling from main method

One.java
public class One {
String asd;
public class() {
asd="2d6"
}
public static void main(String args[]) {
Two a = new Two();
}
}
Two.java
public class Two {
ArrayList<String>data;
String asd;
public Two(String asd){
this.asd=asd;
data.add(this.asd);
}
}
How do I use this asd value of second for third class calling from first class's main method.
**Third class**
Per comments of #Maroun Maroun and #Bennyz, you can create a getter and setter method in your Two class:
import java.util.ArrayList;
public class Two {
ArrayList<String> data;
String asd;
public Two(String asd) {
this.asd = asd;
data = new ArrayList<>(); //<-- You needed to initialize the arraylist.
data.add(this.asd);
}
// Get value of 'asd',
public String getAsd() {
return asd;
}
// Set value of 'asd' to the argument given.
public void setAsd(String asd) {
this.asd = asd;
}
}
A great site to learn about this while coding (so not only reading), is CodeAcademy.
To use it in a third class, you can do this:
public class Third {
public static void main(String[] args) {
Two two = new Two("test");
String asd = two.getAsd(); //This hold now "test".
System.out.println("Value of asd: " + asd);
two.setAsd("something else"); //Set asd to "something else".
System.out.println(two.getAsd()); //Hey, it changed!
}
}
There are also some things not right about your code:
public class One {
String asd;
/**
* The name 'class' cannot be used for a method name, it is a reserved
* keyword.
* Also, this method is missing a return value.
* Last, you forgot a ";" after asd="2d6". */
public class() {
asd="2d6"
}
/** This is better. Best would be to create a setter method for this, or
* initialize 'asd' in your constructor. */
public void initializeAsd(){
asd = "2d6";
}
public static void main(String args[]) {
/**
* You haven't made a constructor without arguments.
* Either you make this in you Two class or use arguments in your call.
*/
Two a = new Two();
}
}
Per comment of #cricket_007, a better solution for the public class() method would be:
public class One {
String asd;
public One(){
asd = "2d6";
}
}
This way, when an One object is made (One one = new One), it has a asd field with "2d6" already.

Help me understand how variables work in Java

I am having problems understanding how private and public variables work.
I am trying to fill the myStorage.outString variable from myThread.
But it seems I cannot see the setInString method from myThread.
Here is my example:
public class CT63_Console extends MIDlet {
public Storage myStorage;
public void startApp() {
this.myStorage = new Storage();
}
}
public class storage{
private String[] outString;
public Storage(){
AClass myThread = new AClass();
myThread.start();
}
public void setInString(String sendString){
this.outString = sendString; //push seems not to be supported by MIDP
}
}
public class AClass{
public void run(){
myFunction("write this into Storage var outString");
}
private myFunction(myString){
myStorage.setInString(myString);
}
}
What do I have to do to set the variable and why am I wrong?
You are trying to access myStorage without having a reference to it.
You could pass this reference when you create the AClass instance.
Also, you are trying to assign a String to an array of Strings which can't be done.
public class Storage{
private String outString;
public Storage(){
AClass myThread = new AClass(this);
myThread.start();
}
public void setInString(String sendString){
this.outString = sendString; //push seems not to be supported by MIDP
}
}
public class AClass {
Storage myStorage;
public AClass(Storage s) {
this.myStorage = s;
}
public void run(){
myFunction("write this into Storage var outString");
}
private myFunction(String myString) {
myStorage.setInString(myString);
}
}
this.outString = sendString;
outString is an array of strings (String[]). You cannot assign a single string to an array of strings. So either you need to change the type of that variable to a single string (just String), or you need to specify an index where you assign that string to. Note that in the latter case you need to initialize the array first.

Categories