I got a obstacle class and there i got this:
public Obstacle(final String name, final String action, final Position position) {
this.name = name;
this.action = action;
this.position = position;
}
In my main class i define an obstacle;
Obstacle trapdoor= new Obstacle("Trapdoor","Open",new Position(3097,3468,0)) ;
How do i retrieve the position from that obstacle? Or more in general how do i get one of those arguments?
You can simply use a getter method, for example :
public Position getPosition()
{
return this.position;
}
In the main class
Obstacle trapdoor= new Obstacle("Trapdoor","Open",new Position(3097,3468,0));
Position pos = trapdoor.getPosition();
You define a method getPosition in the Obstacle class that returns the position. It is called a getter.
You get the position with trapdoor.getPosition().
And you do the same for any member of the class that should be accessible to users of that class.
Like this
public Obstacle(final String name, final String action, final Position position) {
this.name = name;
this.action = action;
this.position = position;
public String getName()
{
return this.name;
}
...
}
In your code:
Obstacle trapdoor= new Obstacle("Trapdoor","Open",new Position(3097,3468,0)) ;
String valueName = trapdoor.getName();
Related
The values I am supposed to pass in:
Name and family should be saved for all instruments
We need to specify whether a strings instrument uses a bow
When I run my code it gives me the error: "constructor Strings in class Strings cannot be applied to given types;"
public class InstrumentTester
{
public static void main(String[] args)
{
/**
* Don't Change This Tester Class!
*
* When you are finished, this should run without error.
*/
Wind tuba = new Wind("Tuba", "Brass", false);
Wind clarinet = new Wind("Clarinet", "Woodwind", true);
Strings violin = new Strings("Violin", true);
Strings harp = new Strings("Harp", false);
System.out.println(tuba);
System.out.println(clarinet);
System.out.println(violin);
System.out.println(harp);
}
}
public class Instrument
{
private String name;
private String family;
public Instrument(String name, String family)
{
this.name = name;
this.family = family;
}
public String getName()
{
return name;
}
public String getFamily()
{
return family;
}
public void setName(String name)
{
this.name = name;
}
public void setFamily(String family)
{
this.family = family;
}
}
public class Strings extends Instrument
{
private boolean useBow;
public Strings(String name, String family, boolean useBow)
{
super(name, family);
this.useBow = useBow;
}
public boolean getUseBow()
{
return useBow;
}
public void setUseBow(boolean useBow)
{
this.useBow = useBow;
}
}
How do I pass in the parameter family if it doesn't take it?
Strings violin = new Strings("Violin", true);
Strings harp = new Strings("Harp", false);
The violin and harp don't get passed a family name when they're created, so the Strings constructor mustn't expect one as an argument.
public Strings(String name, boolean useBow)
What do you pass to super(), then? If all strings belong to the same family then you can hard code the value. Perhaps just "String":
public Strings(String name, boolean useBow)
{
super(name, "String");
this.useBow = useBow;
}
you define strings as one single constructor
public Strings(String name, String family, boolean useBow)
but you try to use it as a different parameters:
Strings violin = new Strings("Violin", true);
either you need to define a second constructor or use the one you created
How do I pass in the parameter family if it doesn't take it?
This sounds like as if you are passing in the family but the class doesn't take it. But the truth is, your class is taking an extra family parameter that is not passed.
Given the comments at the start of main, my interpretation is that you are supposed to give all Strings a family of "Strings". As you can see from the usage in Main, only 2 arguments are passed to the constructor, which means the Strings constructor is not supposed to accept a family parameter.
Therefore, the constructor should be like this:
public Strings(String name, boolean useBow)
{
super(name, "Strings"); // note that I replaced family with "Strings"
this.useBow = useBow;
}
I'm trying to print an arraylist that is in one class, based on one of the parameters from another class. Is this possible?
import java.util.ArrayList;
public class TVShow {
private String title;
private String summary;
private String releaseDate;
private ArrayList<Episode> episodeList;
public TVShow(String title, String summary, String releaseDate) {
this.title = title;
this.summary = summary;
this.releaseDate = releaseDate;
this.episodeList = new ArrayList<>();
}
public void addEpisode(Episode episode) {
episodeList.add(episode);
}
public printEpisodesInSeason(int seasonNr) {
// How can I make this method access the other class and
// print the episodeList by season number?
for (Episode episode : episodeList) {
return System.out.println(episode.);
}
}
}
public class Episode {
private int episodeNr;
private int seasonNr;
private String eTitle;
private int runTime;
public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
this.episodeNr = episodeNr;
this.seasonNr = seasonNr;
this.eTitle = eTitle;
this.runTime = runTime;
}
}
EDIT: I think I misinterpreted the question. You want to only print the episodes from a specific season. This can be done by applying the filter function on the episodeList as follows:
for (Episode episode : episodeList.stream().filter(episode -> episode.getSeasonNr() == seasonNr).collect(Collectors.toList()))
{ ... }
This is ofcourse assuming you apply the getter setter pattern as described below before I edited the answer.
The filter function takes an anonymous function and applies it to all members of a collection. This way, only the episodes which have a season number that is supplied by the user are returned. Then, the foreach loop iterates over the resulting collection.
You could either make the members of Episode public by defining:
public class Episode {
public int episodeNr;
public int seasonNr;
public String eTitle;
public int runTime;
public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
this.episodeNr = episodeNr;
this.seasonNr = seasonNr;
this.eTitle = eTitle;
this.runTime = runTime;
}
}
But this is seen as bad practice. The better way to do it is by defining methods in your Episode class to return the value of the class' fields like for example:
public class Episode {
public int episodeNr;
public int seasonNr;
public String eTitle;
public int runTime;
public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
this.episodeNr = episodeNr;
this.seasonNr = seasonNr;
this.eTitle = eTitle;
this.runTime = runTime;
}
public String getTitle() {
return this.eTitle;
}
}
This practice is called getters and setters and it positively impacts the encapsulation of the code. You could then obtain the value of the Episode's members by calling, for example episode.getTitle().
public abstract class Employee {
String name;
String position
public Employee(String name, String position) {
this.name = name;
this.position = position
}
}
public class Pilot extends Employee {
public Pilot(String name,String position) {
super();
}
public void flight() {//flight the plane}
//getter and setter for the fields
}
public class Attendance extends Employee {
public Attendance(String name,String position) {
super();
}
public Food servingFood(String foodName) {}
}
// there will be many other positions
public class Company {
HashMap<String, ArrayList<Employee>> employeeTable; //values is a list of workers, key is the position
public Company() {this.employeeTable = new HashMap<>();}
public initializeEmployeeTable(file) {} //read file, and create keys in map (file contains information of the position)
public Worker hireEmployee(String position, String name){
if (position.equals("pilot")) {
Pilot p = Pilot(name);
employeeTable.get("pilot").add(p);
return p
}
else if (position.equals("flightAttendance")) {// the else if statement continuous to check the other position; }
}
public Worker callEmployee(String position, String name) {
for ( Employee e : employeeTable.get(position) ) {
if e.getName().equals(name) {
return e;
}
}
return null;
}
public static void main(String[] args) {
Company company = new Company();
company.initializeEmployeeTable(filePath);
File eventFile = new File(filePath); // event file describes what's happening in real world; read the lines, and call the program so that program simulates the real world events
sc = new Scanner(eventFile);
do {
String currentEvent = sc.nextLine();
String[] currentEventParts = currentEvent.split(", ");
if (currentEvent[0].equals("New Airplane")) { // currentEvent looks like {"New Airplane", "Attendance"// this part can be other position name, "Linda"}
Worker w = company.hireEmployee(currentEventParts[1], currentEventParts[2]); }
else if ((currentEvent[0].equals("flying"))) {
Worker w = company.callEmployee(currentEvent[0], currentEvent[1])
if (w.getPosition().equals("Pilot")) {(Worker) w.flight()}
if (w.getPosition().equals("Attendance")) {(Worker) w.serveFood()}
}
}
The reason there is HashMap for employee because there will be many positions; and reading the event file (when the first index is "New Airplane"); I don't want to go check the following index (would be name and position) with so many if statements to create corresponding employee. But when comes to calling specific methods, I need type casting now; since each method can be different (different type parameter, return type); so it's not ideal to have this methods be abstract method in super class employee and have the subclass implements the body.
Any advices: employee data structure; reading file strategy, pattern design would be appreciated. thanks
Here is my field.java class. Ive got the public Field(String name, int number) defined here.
public class Field
{
String name;
int number;
public Field(String name, int number){
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
#Override
public String toString() {
return "Field{" + "name=" + name + ", number=" + number + '}';
}
}
Here is my Player.java class, Im getting an error on my Field currentField = new Field(); - it says that my Field is not defined as a constructor in my Field.java class
public class Player
{
private String name;
private int pos;
Field currentField = new Field();
public Player()
{
}
}
Anyone got a suggestion on why Im throwing errors?
You have provided a parameterized constructor in your class
public Field(String name, int number){
this.name = name;
this.number = number;
}
And hence no default (no-arg) constructor is provided when you define a parametrized constructor.
So when you are trying to create an instance using Field currentField = new Field();, it cannot compile since there is no matching constructor.
Solutions you can try:
1.
Add a no-arg constructor to your class :
public Field()
{
}
Or
2.
While creating an instance, pass values to constrcutor :
Field currentField = new Field("abc", 123);
Yes because your class receiving two arguments name and number and you are trying to create instance of it without passing them.
Either you can pass them
Field currentField = new Field("test", 1); // for ex :
or create a default no arg constructor to your Field class.
/** default no arg constructor **/
public Field(){
// TODO : when there is no param
}
Field currentField = new Field();
You are not passing any arguments to the constructor. You will either need to provide a name and number as parameters, or define a default constructor :
public Field(String name, int number){
this.name = name;
this.number = number;
}
Field currentField = new Field("fieldName", 1);
or
public Field(){
this.name = "";
this.number = 0;
}
Field currentField = new Field();
In every Java class there is a default constructor, if you add any other constructor it will override the default constructor. So to make your code work you have to add no argument constructor.
public Field(){
}
Good morning, I'm using the following constructor code and for some reason the "position" variable sets to null every time a new object is created.
This is my class code
public class Employee
{
private String name;
private int idNumber;
private String department;
private String position;
public Employee(String nam, String depart, String posi, int id)
{
name = nam;
department = depart;
posi = position;
idNumber = id;
}
}
And this is the line I'm using to create the object.
Employee sMeyers = new Employee("Susan Meyers", "Accounting", "Vice President", 47899);
It should be
position = posi;
and not
posi = position;
You're assigning here a null variable (position) to an immutable parameter (posi).
The other answers already stated that your mistake is
posi = position
Luiggi Mendoza also made a comment stating that you should use "this"!
I just want to give you a complete example on how it should be done.
public class Employee
{
private String name;
private int idNumber;
private String department;
private String position;
public Employee(String name, String department, String position, int idNumber)
{
this.name = name;
this.department = department;
this.position = position;
this.idNumber = idNumber;
}
}
Accessing your class variables explicit by this also spares you the hassle of making up new variable names like "nam" and "pos".
For your constructor argument posi, you want to take that value and assign it to one of the class fields which in this example would be position. Now, what you're doing is assigning position (which is null) to posi. So you're overwriting your argument with null and not really doing anything with it.
What you want to do is the following:
position = posi;
which assigns the constructor argument i.e. "Vice President to the class field position.
Remember the variable on the right is assigned to the variable on the left.
Thats because you of this statement:
posi = position;
Change it to
position =posi;
Use "this" pointer to avoid these errors. Happy Coding !!