I am learning Java on my own, i came a cross this interesting example and i found it difficult to understand it.
What i want to know is, what is this called in Java when you have several classes under the same package all of them are Overlapping. Please take a look at the example below ? Note that none of the classes use implements, interface, abstract, extends etc...
And is it possible to find more of these examples ?
class Flightplan
public class Flightplan {
String type;
int seat;
String from;
String to;
// Other local variables, style captain ...
Person[] passenger;
int counter = 0;
Flightplan (String t, int s, String startPlace, String d) {
type = t;
seat = s;
passenger = new Person [s-1]; // kapten tar ett säte
// Captain takes a seat
from = startPlace;
to = d;
}
void book (Person p, String f, String t) {
if (f.equals(from) && t.equals(to)) {
passenger[counter] = p;
to = t;
counter++;
}
else System.out.println(p.name + " try to book a wrong flight !");
}
void flyg() {
System.out.println("On the plane " + this.typ + " reser");
for (int i = 0; i < passenger.length && passenger[i] != null; i++) {
System.out.println(passenger[i].name + ", ");
}
System.out.println("\n");
from = to;
}
}
class Person
public class Person {
String name;
String from;
String to;
String stopover;
int bags;
Flightplan flight;
Person (String n, String f, String m, String t, int v) {
name = n;
from = f;
stopover = m; // Only one stopover is approved, otherwise we would enter this as an array
to = t;
bags = v;
}
void boardNextLeg(Flightplan plan) {
flight = plan;
// Function bar for a stopover due. if-kit building
if (!stopover.equals(null) && flight.from.equals(this.from) && flight.to.equals(this.stopover)) {
System.out.print(this.name + " is now in between");
System.out.println(from + " and " + stopover);
flight.book(this, from, stopover);
}
else if (flight.from.equals(this.from) && flight.to.equals(this.to)) {
System.out.println(from + " och " + to);
flight.book(this, from, to);
}
else System.out.println(this.name + " could not be booked on a flight");
}
}
What is this called in Java when you have
several classes under the same package all of them are Overlapping ?
This is NOT overlapping, rather this is called circular dependency because your Flightplan and Person are dependent on each other, which is bad design and poorly developed.
Basically Circular Dependencies cause lots of issues (like OutofMemoryError) if not properly used, so they should be avoided in between the classes/packages.
You can look here for more details on circular dependencies.
By overlapping you mean that they have member variables with the same names? Each class has a different list of member variables, and one class presents no restrictions to another class.
I think this is called "Several classes that each deal with similar data values"
Related
I'm trying to model a normal PDDL case ,as the logistics example, into a different programming language(java). I'm doing this to understand what are the advantages or disvantages in using PDDL.
This is the PDDL original example
https://github.com/pellierd/pddl4j/wiki/Logistics:-a-simple-running-example
My result is an easy sequential program, shown in the code. My target is to automatize the calculation to obtain a real combinatorial calculation, not a sequential one.
public class logistics {
private static boolean airplaneInUse = false;
private static boolean truckInUse = false;
private static String airport;
private static String place;
private static String city;
private static String pack1;
private static String pack2;
static int state = 0;
public static void main(String args[]) {
if(state == 0) {
start();
System.out.println("The city in the initial state is " + city + "\n");
System.out.println("The airport in the initial state is " + airport + "\n");
}
if(city == "London") {
load_plane();
System.out.println("pk1 and pk2 are on the plane" +"\n");
pack1 = "On Board";
pack2 = "On Board";
}
if(pack1 == "On Board" && pack2 == "On Board") {
fly();
System.out.println("The city after the flight is " + city + "\n");
System.out.println("The airport after the flight is " + airport + "\n");
}
if (city == "Paris") {
unload_plane();
System.out.println("pk1 and pk2 are unloaded from the plane " + "\n");
pack1 = "Unloaded";
pack2 = "Unloaded";
}
if (pack1 == "Unloaded" && pack2 == "Unloaded") {
load_truck();
System.out.println(pack1 + "\n");
System.out.println(pack2 + "\n");
}
if(pack1 == "pk1 On the truck" || pack2 == "pk2 On the truck") {
drive_truck();
System.out.println("Driving to the first place " + "\n");
System.out.println("Driving to the second place " + "\n");
}
if (truckInUse == true) {
unload_truck1();
System.out.println("pk1 delivered in the " + place + "\n");
unload_truck2();
System.out.println("pk2 delivered in the " + place + "\n");
}
}
public static void start() {
city = "London";
airport = "lhr";
return;
}
public static void load_plane() {
city = "London";
pack1 = " pk1 On board";
pack2 = " pk2 On board";
return;
}
public static void fly() {
city = "Paris";
airport = "cdg";
airplaneInUse = true;
return;
}
public static void unload_plane() {
pack1 = "Arrived in Paris";
pack2 = "Arrived in Paris";
airplaneInUse = false;
return;
}
public static void load_truck() {
pack1 = "pk1 On the truck";
pack2 = "pk2 On the truck";
return;
}
public static void drive_truck() {
truckInUse = true;
return;
}
public static void unload_truck1() {
truckInUse = false;
pack1 = "Arrived in South";
place = "South";
return;
}
public static void unload_truck2() {
truckInUse = false;
pack1 = "Arrived in North";
place = "North";
return;
}
}
How can I reach my target? How can I obtain a combinatorial calculation to solve the problem?
I think you are getting at it the wrong way around. Do not try to implement any if/else imperative logic. Declare your actions (aka operators), domain, problem and call a planner to solve it. If you do want to create the domain and problem without encoding it into PDDL and letting the planner (e.g. pddl4j) parse it, you can code it out in Java and hand it over as a coded domain and coded problem.
The structure of your code will be very similar as what you would have put into PDDL, so besides shaving off the parsing time and speeding up the solution time, I do not see much point doing it this way. If you do, keep reading...
See a code example how you call the planner via the pddl4j APIs: https://github.com/pellierd/pddl4j/wiki/A-tutorial-to-develop-your-own-planner#step-6-searching-for-a-solution-plan
Now, normally, you would let the PDDL parser do the job: https://github.com/pellierd/pddl4j/wiki/A-tutorial-to-develop-your-own-planner#step-5-parse-and-encode-the-pddl-domain-and-problem-files
...but if you want to code it out, you will need to declare your actions, domain and problem using the Op, Domain and Problem classes.
Then you call encode the Problem and call one of the planners in pddl4j as indicated in one of the tutorials (links I pasted above). Does this help?
Hi Im trying to set up a person class for each player on a leaderboard, since i dont know how long the leader board is im going to try and loop the amount of people by the count of the rows in the leaderboard. Then im trying to "get" the points for each row and compare each one again the previous to assert the higher number is one the top, ive never used getters and setters before and cant seem to figure out how to do this, any help??
Here is the code for the information i want for each person, I need to find the player_picks, position and player_points . I then need to compare the count of each player_picks total with each player as i go down the leaderboard. If the pick_total is is equal i then need to compare their points total.Ive been trying this for a few weeks but someone suggested it would be easier making a player class and then using get and setters to assign attributes to each of them. SO i could then compare player1 with player 2, player 2 and player 3 etc. Whats making mit difficult is that i dont know the size of the list each time so its confusing me.
Below is the code im using which gives me the attributes im look to "set" but i dont know how to set up a "people" in a person class as the amount of people required each time with be changing (using int size) as a different amount of people join each game.
Im new to this so if im not explaining this well let me know.
public void test_player_leaderboard_entry() {
int size = playerRows.size();
for (int i = 0; i < size; i++) {
//Position
String position_first_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-position-value='" + i + "']")).getText();
//Points
String points_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-points-value='" + i + "']")).getText();
//Username
String username_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-player-value='" + i + "']")).getText();
//Row Number
Integer row = i + 1;
Integer total_of_won_and_looking_good = 0;
//PICKS
for (int pick_number = 1; pick_number < 5; pick_number++) {
String pick_status = Drivers.getDriver().findElement(By.xpath("//*[#id='root']/div/main/section[2]/section/div/ol/a[" + row + "]/li/div[3]/div[" + pick_number + "]/div")).getAttribute("data-qa-pick-state");
//System.out.println(pick_status);
if (Integer.parseInt(pick_status) == 2 || Integer.parseInt(pick_status) == 1) {
total_of_won_and_looking_good = total_of_won_and_looking_good + 1;
}
//System.out.println(total_of_won_and_looking_good);
}
//System.out.println("On row number " + row + " we find " + username_player + " in position " + position_first_player + " with " + total_of_won_and_looking_good + " correct picks and " + points_player + " points!");
}
}
First, you are not attempting to set up a person class for each player on a leaderboard, you are attempting to design a Person class and instantiate a Person object for each person row on the leaderboard. I would heavily suggest reading the Oracle Docs and learning more about classes and objects.
Within your loop you will want to create a new Person object, scrape the necessary value, call the appropriate setter with the value and add that player object to a collection. e.g.
Person p = new Person() //create new Person object
int points = Integer.parseInt(Drivers.getDriver().findElement(By.cssSelector("[data-qa-points-value='" + i + "']")).getText());
p.setPoints(points); //call setter for points field
personList.add(p); //add person to list
An example of a simple person class could look like the following. Note that implementing the Comparable interface allows for Person objects to be sorted when stored in a List or array as seen below.
public class Person implements Comparable<Person> {
private int score;
public Person() { }
public void setScore(int score) { this.score = score; }
public int getScore() { return this.score; }
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
p1.setScore(80);
p2.setScore(90);
List<Person> people = new ArrayList<>();
people.add(p1);
people.add(p2);
System.out.println("Before sorting: " + people.toString());
Collections.sort(people);
System.out.println("After sorting: " + people.toString());
}
#Override
public int compareTo(Person p) {
if (p.getScore() > this.score)
return 1;
if (p.getScore() < this.score)
return -1;
return 0;
}
public String toString() {
return String.format("Person -> score: %d", this.score);
}
}
This question already has answers here:
Having inheritance and polymorphism issues with Java
(2 answers)
Closed 6 years ago.
I am trying to output calclatefee of $2 per day after 3 days. I have switched things around and I am left at this which looks a little sloppy. This Array is also making me take the confusing way.
public class Movie {
String rating;
String title;
int id;
int rentTime;
public String setrating() {
return rating;
}
public void rating(String getrating) {
rating = getrating;
}
public int setid() {
return id;
}
public void id(int agetid) {
id = agetid;
}
public String settitle() {
return title;
}
public void title(String gettitle) {
title = gettitle;
}
public int setfees() {
return rentTime;
}
public void fees(int getrentTime) {
rentTime = getrentTime;
}
public Movie() {
title = " ";
rating = " ";
id = 0;
rentTime = 0;
System.out.println("default constructor");
}
public Movie(String title, String rating, int id, int rentTime) {
title = " not overridden ";
rating = " NR ";
id = 0;
rentTime = 0;
System.out.println("Overloaded -" + title + rating + id + rentTime);
}
public static void main(String[] args) {
Movie[] Array = {
new Action(" The 100", " pg-13", 105, 7, 3),
new Comedy(" Supernatural", " pg-13", 5, 2, 0),
new Drama(" Lost 2", " R", 9, 2, 0) };
for (int x = 0; x < Array.length; x++) {
// System.out.println(x);
System.out.println(Array[x].toString());
}
}
}
public abstract class Action extends Movie {
protected double latecost;
protected double latefees = 3;
public Action(String gettitle, String getrating, int getid, int getrentTime, double latecost) {
super(gettitle, getrating, getid, getrentTime);
title = gettitle;
rating = getrating;
id = getid;
rentTime = getrentTime;
latecost = latefees;
System.out.println("Overridden " + title + rating + " " + id + " " + " " + rentTime + " "
+ latecost);
}
public double calclatefees(double latecost, double rentTime) {
if (rentTime > 3)
latefees = ((rentTime - 3) * latecost);
return latefees;
}
#Override
public String toString() {
String x = "\nMovie: " + title + " is rated " + rating + "\nMovie ID number: " + id
+ " and the late fee for action movies is $" + latecost + "\n";
return x;
}
protected void finalize() throws Throwable {
try {
System.out.println("Finalize method");
} finally {
super.finalize();
}
}
public void dispose() {
System.out.println(" dispose method");
}
}
Problems:
There's no calclatefee method to override in the parent class. If you want a child class to override method, it must be present in the parent class, at least as an abstract method (if the parent is abstract or is an interface).
You never call your calclatefee method anywhere, so you shouldn't expect to ever see its result in your output.
Your child class, Action, is abstract -- isn't that backwards? Most often its the parent class that's abstract, so why are you structuring it this way? And as written your main method shouldn't compile since you seem to be trying to create an instance of an abstract class.
Your class overrides the finalize() method, something that is generally not recommended. Fortunately your override doesn't really do anything other than output to the standard out and then call the super's method, but still, why risk it?
Side issues
Your code does not follow Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
You will want to try to improve the formatting of your code that you post in here and your code in general. Good formatting including using an indentation style that is uniform and consistent will help others (us!) to better understand your code, and more importantly, it will help you to better understand your code and thus fix your own bugs. Also it shows that you're willing to put in extra effort to make it easier for the volunteers here to help you, and that effort is much appreciated. I took the liberty of trying to fix this for you.
Hey there Stackoverflowers,
I just started programming in Java and encountered a strange problem concerning printing an object. When a new object of type gast is created the user has to enter his or her birthday. This al works fine, however, if I try to print it out I returns 0-0-0. Why is that? By the way, if I create a new datum directly with the parameter constructor it works fine. Wherein lays the problem? I just can't figure it out. I hope you guys can help me out.
Thanks in advance!
public class Datum {
private static String patroon = "\\d{2}-\\d{2}-\\d{4}";
public int dag;
public int maand;
public int jaar;
Datum(int dag, int maand, int jaar) {
System.out.print("constructor: " + dag);
this.dag = dag;
System.out.println(", dag: " + this.dag);
this.maand = maand;
this.jaar = jaar;
}
Datum() {
newDatum();
}
/* */
public static Datum newDatum() {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
Datum datum = new Datum(dag, maand, jaar);
System.out.println(datum);
return datum;
}
else {
return new Datum();
}
}
public String toString() {
return this.dag + "-" + this.maand + "-" + this.jaar;
}
}
Second class:
Gast() {
this.firstName = Opgave5.userInput("Voornaam gast");
this.lastName = Opgave5.userInput("Achternaam gast");
this.geboortedatum = new Datum();
System.out.println("gast: " + this.geboortedatum); // <--- this prints out 0-0-0
}
public String toString() {
return this.firstName + " " + this.lastName + " " + this.geboortedatum;
}
I think you don't understand constructors in Java. You are merely ignoring the result of newDatum() in the constructor. Also, if it did have the expected effect, it might recurse infinitely in the constructor invocation inside newDatum(). Use something like this; allowing newDatum() to edit the instance will work:
Datum() {
newDatum(this);
}
public static void newDatum(Datum instance) {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
instance.dag = dag;
instance.maand = maand;
instance.jaar = jaar;
System.out.println(instance);
}
else {
new Datum();
}
// ^^ Above code may be buggy, see my answer above code
}
This line:
this.geboortedatum = new Datum();
Is using the default constructor. This will set no values. Try to pass the parameters in via constructor like this:
this.geboortedatum = new Datum(1, 2, 3);
If you want to take advantage of the static method you wrote (which is where you ask for user input), then do the following:
this.geboortedatum = Datum.newDatum();
I want to put State objects (which are HashMaps with Character as key and State as Value into an ArrayList named allStates. Should I override the equals and hashCode methods here? Why? How?
This code is for the Automaton and State classes I've built so far:
class State extends HashMap<Character, State>{
boolean isFinal;
boolean isInitial;
int stateId;
State () {
isInitial=false;
isFinal = false;
}
public boolean equals (Object o){
boolean isEqual = false;
State compare = (State)o;
if ((compare.stateId)==this.stateId)
{
return true;
}
return isEqual;
}
public int hashCode() {
int theHashCode = stateId%7;
return theHashCode;
}
}
class Automaton{
List <State> allStates;
//private List<State> finalStates;
int theInitialStateIntIndex;
State actualState;
char [] alphabet;
Automaton() {
allStates = new ArrayList<State>();
}
public void setAllStates (int numberOfStates) {
for (int i =0; i <numberOfStates; i++) {
State newState = new State();
newState.stateId = i;
allStates.add(newState);
}
}
public void setAlphabet (String alphabetLine){
alphabet = alphabetLine.toCharArray();
}
public void markFinalStates (String [] finalStates){
for (int index =0; index<finalStates.length; index++) {
int aFinalStateId = Integer.parseInt(finalStates[index]);
State aFinalState = allStates.get(aFinalStateId);
aFinalState.isFinal = true;
allStates.add(aFinalStateId, aFinalState);
/*DEBUG*/
aFinalState = allStates.get(aFinalStateId);
if ((aFinalState.isFinal)==true)
System.out.println("THE STATE " + aFinalStateId + " IS MARKED AS FINAL");
}
}
public void markInitialState (int initialStateId) {
State theInitialState = allStates.get(initialStateId);
theInitialState.isInitial=true;
allStates.add(initialStateId, theInitialState);
theInitialStateIntIndex = initialStateId;
/*DEBUG*/
System.out.println("THE INITIAL STATE ID IS " + initialStateId);
theInitialState = allStates.get(initialStateId);
if ((theInitialState.isInitial)==true)
System.out.println("THE STATE " + initialStateId + " IS MARKED AS INITIAL");
}
public void setTransitions(int stateId, String transitionsLine){
State theOneToChange = allStates.get(stateId);
String [] statesToReachStringSplitted = transitionsLine.split(" ");
for (int symbolIndex=0; symbolIndex<statesToReachStringSplitted.length;symbolIndex++){
int reachedState= Integer.parseInt(statesToReachStringSplitted[symbolIndex]);
theOneToChange.put(alphabet[symbolIndex],allStates.get(reachedState));
System.out.println("THE STATE " + stateId + " REACHES THE STATE " + reachedState + " WITH THE SYMBOL " + alphabet[symbolIndex]);
}
allStates.add(stateId, theOneToChange);
}
public int findInitialState(){
int index =0;
cycle: for (; index<allStates.size(); index++){
State s = allStates.get(index);
if (s.isInitial==true) {
break cycle;
}
} return index;
}
public void processString (String string)
{
StringBuilder stepString= new StringBuilder (string);
int actualStateIntIndex;
System.out.println("THE FOUND INITIAL ONE IS "+ theInitialStateIntIndex);
State firstState = allStates.get(theInitialStateIntIndex);
actualState = firstState;
while (stepString.length()>0){
Character characterToProcess = stepString.charAt(0);
stepString.deleteCharAt(0);
State nextState;
nextState = ((State)actualState.get(characterToProcess)); // pasa al siguiente State
actualState = nextState;
actualStateIntIndex=allStates.indexOf(actualState);
System.out.println("the actual state for " + stepString + " is " + actualStateIntIndex);
if ((actualState.isFinal==true) && (stepString.length()==0))
{
System.out.println("THE STRING " + string + " IS ACCEPTED AT STATE " + actualStateIntIndex );
}
else if (stepString.length()==0 && (actualState.isFinal==false)){
System.out.println("THE STRING " + string + " IS REJECTED AT STATE " + actualStateIntIndex);
}
}
}
}
If the automaton is a DFA, then one can use the Accessing String to ID the field.
An accessing String is any string that could be used to reach the state from the start state. One will have to build the string while building the DFA, however, it won't add more time complexity. (Yes, one then needs to hashcode/equal the string)
Or actually, ID the states by an increasing serial number/string should work for all automaton. Then hashcode/equal based on the ID.
Go for the 2nd one, easier and works better than 1, unless you want to take care of the duplicated states.
Yes, you need the hashcode and equals for a user defined type to work with hash.