I try to write recursive function which gets an array of flights and returns all the possible paths from source country to dest country.
The function signature in Java:
List<List<String>> printAllPathsUtil(String src, String d,List<Flight> localPathList)
every object of type Flight contain 2 features from and to.
I succeed to write the below code and its run successfuly,but I sent to the function one more parameter : String help -who store the source country.
public List<List<String>> printAllPathsUtil(**String help**,String src, String d,List<Flight> localPathList)
I would appreciate it if someone could please find a way how to use the function without the extra parameter,and show in the code.
Note:I implemented the classes in a minimal way just to have parameters to send to the function, therefore there is no get and set in the classes.
import java.util.ArrayList;
import java.util.List;
public class flligth {
public static void main(String args[]) {
Flight f1 = new Flight("ISRAEL","ROMANIA");
Flight f2 = new Flight("ISRAEL","HOLAND");
Flight f3 = new Flight("ISRAEL","LONDON");
Flight f4 = new Flight("ISRAEL","U.S.A");
Flight f5 = new Flight("HOLAND","LONDON");
Flight f6 = new Flight("LONDON","ROMANIA");
all_flight all_f=new all_flight(6);
all_f.addEdge(f1);f1.print();
all_f.addEdge(f2);f2.print();
all_f.addEdge(f3);f3.print();
all_f.addEdge(f4);f4.print();
all_f.addEdge(f5);f5.print();
all_f.addEdge(f6);f6.print();
List <Flight> localPathList=new ArrayList<>();
all_f.printAllPathsUtil("ISRAEL","ISRAEL","ROMANIA",localPathList);
}
}
class Flight{
String from;
String to;
public Flight(String from ,String to){
this.from=from;
this.to=to;
}
public void print()
{
System.out.print(from+" ");
System.out.println(to);
}
}
class all_flight{
static int current=0;
// adjacency list
public ArrayList<Flight> f;
int index;
// Constructor
public all_flight(int index){
this.index=index;
initFlight();
}
// utility method to initialise
// f list
private void initFlight()
{
f = new ArrayList<Flight>();
}
// add edge from u to v
public void addEdge( Flight path)
{
// Add to list.
f.add(path);
}
public List<List<String>> printAllPathsUtil(String help,String src, String d,List<Flight> localPathList)
{
Flight now = f.stream()
.filter(a -> a.from.equals(src)).findFirst()
.orElse(new Flight("no from","no to"));
if(now.from.equals("no from")){
f.remove(0);
localPathList.clear();
if(!(f.isEmpty())){
return printAllPathsUtil(help,f.get(0).from,d,localPathList);
}
return null;
}
localPathList.add(now);
if(localPathList.get(localPathList.size()-1).to.equals(d)
&& localPathList.get(0).from.equals(help)){
System.out.println("the path is :");
printPath(localPathList);
}
return printAllPathsUtil(help,now.to,d,localPathList);
}
private static void printPath(List<Flight> path)
{
for(Flight v : path)
{
v.print();
}
System.out.println();
}
}
Whenever you invoke the printAllPathsUtil() function, you're passing the same value of help each time. Since the property stays constant for each recursive call, you can simply remove it from the parameters.
Instead, you can create a class attribute origin, and replace the usage of help in the function with self.origin.
If localPathList is empty, then help is src. Otherwise, it's localPathList.get(0).from.
Related
I have a problem. I have the following class:
public class Candlestick {
private double ma5;
private double ma10;
private double ma17;
public void setMA5(double value) {
this.ma5 = value;
}
public void setMA10(double value) {
this.ma10 = value;
}
public void setMA17(double value) {
this.ma17 = value;
}
}
Then I also have the following array:
public static List<Integer> mas = List.of(5, 10, 17);
Now in my code I have a for loop that loops through the mas list, like this:
Candlestick candlestick = new Candlestick();
for (int ma : mas) {
// UPDATE THE CORRECT MA VALUE IN THE CANDLESTICK CLASS
candlestick.setMA ????
}
But I need to update the attribute of the class I am currently on in the loop. How can I prorammatically build up the setMA() function?
You can utilize Java Reflection.
Candlestick candlestick = new Candlestick();
for (int ma : mas) {
Method setMaMethod = Candlestick.class.getDeclaredMethod("setMA" + ma, double.class);
setMaMethod.invoke(candlestick, 1.0);
}
This code invokes setMA* passing 1.0 as a function argument.
The most common approach to acquire methods depending on a variable would be to use reflection - the getMethod(String name, Class<?>... parameterTypes) method for example.
However, for your example I think a Map with a Integer key would be more suitable than every reflection.
That would leave us with the following Candlestick class (main method just for testing):
import java.util.Map;
import java.util.TreeMap;
public class Candlestick {
private Map<Integer, Double> masses;
public Candlestick()
{
masses = new TreeMap<>();
}
public Map<Integer, Double> getMasses() {
return masses;
}
public Double getMassValue(int key)
{
return masses.get(key);
}
public void setMassValue(int key, double value)
{
masses.put(key, value);
}
public static void main(String[] args)
{
Candlestick candlestick = new Candlestick();
candlestick.setMassValue(5, 13.37);
System.out.println(candlestick.getMassValue(5));
}
}
This would also allow you to easily iterate over the masses (or whatever MA is supposed to mean, that's why someone should use proper variable names ;)).
I have a class with this, it's an example code, not the real code
private static String className;
public static Wish getInstance(Class<?> clazz) {
if(wish == null)
wish = new Wish();
className = clazz.getName();
return wish;
}
Many classes use this Wish class, then each class should "say" a wish with the className passed in the getInstance method.
Then I have something like this
public class Boy {
private Wish w = Wish.getInstance(Boy.class);
//at this moment the static variable take "com.package.Boy" value
....
}
Another classs
public class Girl {
private Wish w = Wish.getInstance(Girl.class);
//at this moment the static variable take "com.package.Girl" value
....
}
When everybody start to say their wishes, example
public class WishesDay {
private Girl g;
private Boy b;
public void makeYourWish() {
g = new Girl(); //get the com.package.Girl value
b = new Boy(); //get the com.package.Boy value
//sample output "com.package.Boy wants A pink house!"
g.iWish("A pink house!"); // the boys don't want this things :(
b.iWish("A spatial boat!");
}
}
I know that each object have the same copy o the Wish class and the static variable className change when each object (Girl, Boy) call the Wish.getInstance(Class<?> clazz) method.
How can I use a static variable (I want avoid to instantiate the Wish class) and keep the correct value for the variable className.
Can I make this with a static variable? or the solution is to instantiate (no static variable)
For example, log4j has the Logger class, I want to make the same thing with the class name.
You'll have to make your constructor private if you want to avoid instantiate the Wish class and make the className not static.
public class Wish {
String className;
private Wish(String className){
this.className = className;
}
public static Wish getInstance(Class<?> clazz) {
String className = clazz.getName();
return new Wish(className);
}
public String getClassName() {
return className;
}
}
package com.test;
public class WishesDay {
private Girl g;
private Boy b;
public void makeYourWish() {
g = new Girl(); //get the com.package.Girl value
b = new Boy(); //get the com.package.Boy value
//sample output "com.package.Boy wants A pink house!"
g.iWish("A pink house!"); // the boys don't want this things :(
b.iWish("A spatial boat!");
}
public static void main(String[] args) {
WishesDay wd = new WishesDay();
wd.makeYourWish();
//outputs com.test.Girl wants A pink house!
//com.test.Boy wants A spatial boat!
}
}
i have the following problem: I read out database items in an observable list. Now I want to display some items from the selected line in a few textfields on the right side of my tableview.
I got the observable-line-index with the following code, but I want to select an other column of the line.
AnalysemethodenTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Object>() {
public void changed(ObservableValue<?> observable, Object oldvalue, Object newValue) {
index.set(analysemethodendata.indexOf(newValue));
databaseIndex = (analysemethodendata.indexOf(newValue) + 1);
System.out.println("Index:\t" + databaseIndex);
}
});
I found the following code: Click
But i don't understand this. It's something like to write a new list and place a copy of the items of the observable list in this new list.
I think, if I have the index of the line with my code, I can select the other items in the line of the observable list, too (I thought like "x,y" like an array)
If i cast it to String, the output is only machine code.
Hope I can understand the solution with your help!
EDIT: I inserted the following code:
System.out.println(analysemethodendata.get(databaseIndex).toString());
But I only get machine code in my Output:
table.analysemethoden_table#63c0d5b7
EDIT 2:
Table-Controller-Code:
package table;
import javafx.beans.property.SimpleFloatProperty;
import javafx.beans.property.SimpleStringProperty;
public class analysemethoden_table {
private final SimpleStringProperty rAmnorm;
private final SimpleStringProperty rMethverantw;
private final SimpleFloatProperty rBestimmungsgrenze;
private final SimpleFloatProperty rNachweisgrenze;
public analysemethoden_table (String sAmnorm, String sMethoverantw, Float sBestimmungsgrenze, Float sNachweisgrenze) {
this.rAmnorm = new SimpleStringProperty(sAmnorm);
this.rMethverantw = new SimpleStringProperty(sMethoverantw);
this.rBestimmungsgrenze = new SimpleFloatProperty(sBestimmungsgrenze);
this.rNachweisgrenze = new SimpleFloatProperty(sNachweisgrenze);
}
// Getter- und Setter-Methoden
/** rAmnorm **/
public String getRAmnorm() {
return rAmnorm.get();
}
public void setRAmnorm(String set) {
rAmnorm.set(set);
}
/** rMethverantw **/
public String getRMethverantw() {
return rMethverantw.get();
}
public void setRMethverantw(String set) {
rMethverantw.set(set);
}
/** rBestimmungsgrenze **/
public Float getRBestimmungsgrenze() {
return rBestimmungsgrenze.get();
}
public void setRBestimmungsgrenze(Float set) {
rBestimmungsgrenze.set(set);
}
/** rNachweisgrenze **/
public Float getRNachweisgrenze() {
return rNachweisgrenze.get();
}
public void setRNachweisgrenze(Float set) {
rNachweisgrenze.set(set);
}
}
You need to use
analysemethodendata.get(databaseIndex).getRAmnorm();
or any other getter method in place of getRAmnorm() to get the required output.
databaseIndex -> row number
Back ground: I am pairing up two pieces of data, both Strings, into an ArrayList. Therefore I am storing the paired data into an object, and then storing this object into an ArrayList. I have a text file that for each word, I am assigning a number to. The paired data is then word-number (but I have typed them both as String). I do not know how many objects I will need for any given file size.
How do I set up a logic to iterate through the text file and populate my ArrayList. This is what I have done so far:
The : PredictivePrototype.wordToSignature(aWord)// converts the word into a number signature e.g "4663" for a word like "home"
public class ListDictionary {
private static ArrayList<WordSig> dictionary;
public ListDictionary() throws FileNotFoundException {
File theFile = new File("words");
Scanner src = new Scanner(theFile);
while (src.hasNext()) {
String aWord = src.next();
String sigOfWord = PredictivePrototype.wordToSignature(aWord);
// assign each word and its corresponding signature into attribute
// of an object(p) of class WordSig.
//WordSig p1 = new WordSig(aWord, sigOfWord);
//Then add this instance (object) of class Wordsig into ArrayList<WordSig>
dictionary.add(new WordSig(aWord, sigOfWord));
}
src.close();
}
Other class to which paired data is stored:
public class WordSig {
private String words;
private String signature;
public WordSig(String words, String signature) {
this.words=words;
this.signature=signature;
}
}
Your code seems to be OK. With ArrayList you can add as many elements as you want (by using add() function).
Here is an example:
import java.util.ArrayList;
public class ListDictionary {
public class WordSig {
private String words;
private String signature;
public WordSig(String words, String signature) {
this.words=words;
this.signature=signature;
}
public String getWords() {
return words;
}
public String getSignature() {
return signature;
}
}
private static ArrayList<WordSig> dictionary = new ArrayList<WordSig>();
public ListDictionary() {
// add as many as you want
for ( int i=0; i < 10; i++)
dictionary.add(new WordSig("key"+i, "value"+i));
}
public static class testListDictionary {
public static void main(String[] args) {
new ListDictionary();
// test output
for ( int i=0; i < dictionary.size(); i++ )
System.out.println( "<" + dictionary.get(i).getWords() + "|"
+ dictionary.get(i).getSignature() + ">");
}
}
}
So I have a List of Actors and I want to get each Actors dynamic class name.
For example here is my Actor list: People, Birds, Cows.
I want to get as result the same: "People, Birds, Cows" but without a name attribute in the Actors class. Is it possible?
Example code (here instead of list I used array) :
public Area map[][];
map[0][0] = new AntHillArea();
String name = map[0][0].getClass().getName(); //this results "Area" instead of AntHillArea
Edit: There was other problems with the code, getClass().getName() works fine. Thanks anyway.
String className = obj.getClass().getSimpleName();
Update:
public class Test {
public static void main(String[] args) {
Area map[][] = new Area[1][1];
map[0][0] = new AntHillArea();
String name = map[0][0].getClass().getSimpleName(); // returns "AntHillArea"
System.out.println(name);
}
}
class Area {
}
class AntHillArea extends Area {
}
Use getSimpleName method. It gives you only class and will remove any package if having.
You can do this:
class Dog
{
//code
public String getName()
{
return Dog.class.getName();
}
//better
#Override
public String toString()
{
return Dog.class.getName();
}
}
And similarly for each class. Or have a global one as mentioned in other answers as:
public static String getClassName(Class<?> clas){
return clas.getName();
}
To use Dog dog = new Dog(); getClassName(dog.class);