I start with OOP
And i have following problem:
I made a new class
Then I made ainstance from this class
Now, for every instance I want to do something
I tried it with a for each loop but it doesn't work...
There are some syntax problems
This is the class:
package main;
public class command
{
String call;
String execute;
}
And this from the Main class:
private static void load() {
command greeting = new command();
greeting.call = "hello";
greeting.execute = "Hello Sir";
for (command c: command) {
System.out.println("Another command...");
}
}
I don't know how to make the loop or is there another way to do it?
You can create a static list inside class command that the instances get added to in the constructor(s). Then you'll always have references to whatever instances are created.
Here's an example:
import java.util.List;
import java.util.ArrayList;
public class command
{
String call;
String execute;
public static List<command> commands = new ArrayList<>();
public command() {
commands.add(this);
}
public command(String call, String execute)
{
this.call = call;
this.execute = execute;
commands.add(this);
}
public String toString()
{
return "call: " + call + " | execute: " + execute;
}
}
Driver class:
public class driver
{
public static void main(String[] args)
{
for(int i = 1; i <=10; i++)
{
command c = new command("call" + i, "execute" + i);
}
for(command cmd: command.commands)
{
System.out.println(cmd);
}
}
}
Output:
The syntax you are using in your for loop must use a instance of a class that implements the Iterable interface. For example you can use implementations of the List interface.
For example, you can try:
private static void load() {
command greeting = new command();
greeting.call = "hello";
greeting.execute = "Hello Sir";
List<command> listOfCommands = new ArrayList<>();
listOfCommands.add(greeting);
for (command c: listOfCommands) {
System.out.println("Another command...");
}
}
Related
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);
}
}
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.
Im pretty new to Java. I'm trying to connect these classes together. The Go class, is the main class, that should end up running the program. According to Eclipse, the program doesn't contain any errors, but while running, the outprint is blank.
The Go class:
public class Go {
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
}
}
The Ansat class:
import java.util.ArrayList;
public class Ansat {
public String navn;
public int alder;
public Ansat(String navn, int alder, ArrayList<Ansat> ansat){
this.navn = navn;
this.alder = alder;
}
public int getAlder() {
return alder;
}
public void setAlder(int alder) {
this.alder = alder;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
}
The Data class:
import java.util.ArrayList;
public class Data {
private ArrayList<Ansat> ansat;
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
}
public ArrayList<Ansat> getAnsat() {
return ansat;
}
}
Output the contents of ArrayList to console
public class Go {
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
for(Ansat ansat : getAnsat()){
system.out.println(ansat.getNavn(), ansat.getAlder());
}
}
}
I recommend just two modifications for you to get a proper readable output.
Add the following method to your Ansat class
//modify the returned string however you want it to appear
public String toString() {
return navn + " , " + alder;
}
and then add this line in your main method of Go class (last statement)
System.out.println(klasseObject.getAnsat().get(0).toString());
The toString() class that is added to the Ansat is overriding the toString() method for Ansat meaning that it allows you to print the fields of Ansat class the way you want it and whenever you invoke toString() on object of Ansat then it will pretty print it for you such as below:
Hej , 123
You can update the toString() method to print it however you want.
If you wish to have more than one element in your ArrayList then you have to do the following changes (but, I do want state that you are not doing this the right way):
Data klasseObject = new Data();
klasseObject.infoListe();
Data klasseObject2 = new Data();
klasseObject.infoListe();
Data klasseObject3 = new Data();
klasseObject.infoListe();
for(Ansat s: klasseObject.getAnsat())
System.out.println(s.toString());
And this changes to your Data class
public void infoListe(){
if(ansat != null) {
ansat.add(new Ansat("Hej", 123, ansat));
} else {
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
}
}
If I were to review your code and suggest improvements, then I would do the following changes in your classes (copy/paste the following code Go.java file and run it):
import java.util.ArrayList;
public class Go {
public static void main(String[] args) {
// running below creates an ArrayList<Ansat> that is inside KlasseObject
Data klasseObject = new Data();
// creates one Ansat(Hey,123) and add it to list
klasseObject.setData("Hey", 123);
// creates one Ansat(Raf,555) and add it to list
klasseObject.setData("Raf", 555);
// creates one Ansat(X-men,999) and add it to list
klasseObject.setData("X-men", 999);
//as many classes as you want, it would add them all to the list
//of klasseObject
// now that we set three Ansats, we will retrieve the list and print
// them all
for (Ansat s : klasseObject.getAnsatList())
System.out.println(s.toString());
}
}
class Ansat {
public String navn;
public int alder;
//remove the array list from constructor, not needed
public Ansat(String navn, int alder) {
this.navn = navn;
this.alder = alder;
}
public int getAlder() {
return alder;
}
public void setAlder(int alder) {
this.alder = alder;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
//overrided toString method to pretty-print Ansat object
public String toString() {
return navn + " , " + alder;
}
}
class Data {
private ArrayList<Ansat> ansat;
// added the constructor for Data to initialize Data with empty list
public Data() {
ansat = new ArrayList<Ansat>();
}
//replaced infoListe to setData and added args to it so you can
//pass them from main method
public void setData(String name, int age) {
// every time setData is called a new Ansat is added to list
Ansat a = new Ansat(name, age);
ansat.add(a);
}
public ArrayList<Ansat> getAnsatList() {
return ansat;
}
}
Actually the process what you have followed is perfectly correct,But your getting blank because your not printing the arraylist, hence your getting blank output. Just add the below line and you will see the correct output.
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
System.out.println(ansat);
}
or in the main function just use it like this...
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
System.out.println(klasseObject.getAnsat());
}
Even iterating over array list will fetch you the output -
for (Ansat ansatLoop : klasseObject.getAnsat()) {
System.out.println(ansatLoop.getAlder() + ":"
+ ansatLoop.getNavn());
}
I hope this would solve your query.
Your code is working Perfectly! It has no
System.out.println();
anywhere in the methods that run.
If you modify the method infoListe() to add a println it will print something out
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
System.out.println("Element Added to ArrayList");
}
I'm completely new to Java and I'm trying to set up a test for it. But how do I call a method from the test class?
Right now I'm trying with a public method, and making a new instance of the class Hangman, but the call to the method doesn't work.
Hangman.java:
public class Hangman extends Applet implements ActionListener{
public String[] getWordArray(){
/* Enter the wordslist, separated by a | here: */
String str = "computer|"
+ "radio|"
+ "calculator|"
+ "teacher|"
+ "bureau|"
+ "police|"
+ "geometry|"
+ "president";
String[] temp;
/* delimiter */
String delimiter = "\\|";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
return temp;
}
}
HangmanTest.java:
public class HangmanTest {
Hangman hangman = new Hangman();
#Before
public void setUp() throws Exception {
}
#After
public void tearDown() throws Exception {
}
#Test
public void testGetWordArray() {
int expected = 8;
int actual = hangman.getWordArray().length();
Assert.assertEquals(expected, actual);
}
}
You have a syntax error. It is int actual = hangman.getWordArray().length;, not int actual = hangman.getWordArray().length();. The length of array is an attribute, not a method. All other datastructures (like ArrayList) have a method for this.
Just want to use java hashmap to cache a simple pair into memory and want to get the cached data in another instance.
I am using the below code to put some datas into cache consider the below ProcessDefinitionJavaCode.java code.
package Folder.ProcessDefinition;
import java.util.*;
import java.io.*;
public class ProcessDefinitionJavaCode{
/****** START SET/GET METHOD, DO NOT MODIFY *****/
protected String string_1 = "";
protected String string_2 = "";
public String getstring_1() {
return string_1;
}
public void setstring_1(String val) {
string_1 = val;
}
public String getstring_2() {
return string_2;
}
public void setstring_2(String val) {
string_2 = val;
}
/****** END SET/GET METHOD, DO NOT MODIFY *****/
public ProcessDefinitionJavaCode() {
}
public void invoke() throws Exception {
/* Available Variables: DO NOT MODIFY
In : String string_1
In : String string_2
* Available Variables: DO NOT MODIFY *****/
HashMap<Integer,String> cache = new HashMap<Integer,String>();
cache.put(21, "Twenty One");
cache.put(31, "Thirty One");
}
}
What should I be doing If I want to get the datas I added just now in cache
in another java class temp.java.
I am sorry if it is very silly, I am not a Java expert..
You pass the cache Hashmap to the other class in a constructor or a setter method.
HashMap<Integer,String> cache = new HashMap<Integer,String>();
cache.put(21, "Twenty One");
cache.put(31, "Thirty One");
NewClass newClass = new newClass(cache);
or
NewClass newClass = new newClass();
newClass.setCache(cache);
How about this simple approach (it may be not exactly what you want, but you may get an useful idea):
class PairOfStrings {
final String a, b;
PairOfStrings(String a, String b) {
this.a = a;
this.b = b;
}
#Override
public String toString() {
return "PairOfStrings{" +
"a='" + a + '\'' +
", b='" + b + '\'' +
'}';
}
}
class Sample {
public static void main(String[] args) {
HashMap<Integer, PairOfStrings> pairs = new HashMap<Integer, PairOfStrings>();
pairs.put(1, new PairOfStrings("first", "second"));
pairs.put(2, new PairOfStrings("third", "fourth"));
System.out.println(pairs.get(1));
}
}
The only method I know to retrieve the values from a map is creating a function to do so.
That way you can create a function like this:
String[] getValues(){
String[] aux=new String[cache.size()];
int i=0;
for (Integer integer : cache.keySet()) {
aux[i++]=cache.get(integer);
}
System.out.println(Arrays.toString(aux));
return aux;
}