I'm trying to create a class which answers the question below:
Write a class to represent athlete records for an athletics club. An athlete record consists of a name, personal best (a floating point number) and discipline (e.g. sprinter, javelin, long jump etc). Once an athlete record has been created it should be possible to change the personal best and discipline but not the name.
I'm getting the error incompatible types in the line:
return personal();
Why is this?
public class AthleteRecords{
private String name;
private int personal;
private String discipline;
public AthleteRecords(String n, int p, String d){
name = n;
personal = p;
discipline = d;
}
public void setPersonal(int p){
personal = p;
}
public void setDiscipline(String d){
discipline = d;
}
public String getName(){
return name;
}
public String getPersonal(){
return personal;
}
public String getDiscipline(){
return discipline;
}
}
Related
I am working on my class assignment and I am stuck.
I have two classes: Part, which is abstract and has InHouse and Outsourced classes that extend Part. Then I have Product, which oddly has an observableArrayList of parts called associatedParts.
I am working on my AddProductController, trying to make a call to the method in the Product class addAssociatedPart(). My problem is the compiler doesn't find the method in Part. If I cast to an InHouse, it doesn't find the method in InHouse, and so on. I can't use a static method, because the method addAssociatedPart() is supposed to be non-static per the UML design. So, I can't tell it explicitly to find it in Product.addAssociatedPart(), because it tells me I can't reference a non-static etc.
Here's the code snippets starting with the Product class.
public class Product {
private ObservableList<Part> associatedParts = FXCollections.observableArrayList();
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
public void addAssociatedPart(Part part) {
getAllAssociatedParts().add(part);
}
public ObservableList<Part> getAllAssociatedParts() {
return this.associatedParts;
}
And then the AddProductScreenController class:
public class AddProductScreenController implements Initializable {
#FXML
public void onAddProductAddPart(ActionEvent event) {
// this is triggered when the Add button is clicked
Part selectedItem = addProductTableViewAll.getSelectionModel().getSelectedItem();
selectedItem.addAssociatedPart(); // can't find method
Product.selectedItem.addAssociatedPart(); // can't find variable selectedItem (obviously bad formatting)
selectedItem.Product.addAssociatedPart(); // can't find variable Product (again bad formatting)
addAssociatedPart(selectedItem); // can't find method addAssociatedPart()
Product.addAssociatedPart(selectedItem); // non-static method, can't be referenced from a static context
InHouse newPart = new InHouse(1, "test", 1.99, 1, 1, 1, 101);
addAssociatedPart(newPart); // can't find method
Product.addAssociatedPart(newPart); // non-static method
newPart.addAssociatedPart(); // can't find method
addProductTableViewPartial.setItems(associatedParts);
}
}
The part code as requested:
public abstract class Part {
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
public ObservableList<Part> allParts = FXCollections.observableArrayList();
public Part(int id, String name, double price, int stock, int min, int max) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
this.min = min;
this.max = max;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return this.price;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getStock() {
return this.stock;
}
public void setMin(int min) {
this.min = min;
}
public int getMin() {
return this.min;
}
public void setMax(int max) {
this.max = max;
}
public int getMax() {
return this.max;
}
}
This is InHouse
package model;
public class InHouse extends Part {
private int machineId;
public InHouse(int id, String name, double price, int stock, int min, int max, int machineId) {
super(id, name, price, stock, min, max);
this.machineId = machineId;
}
public void setMachineId(int machineId) {
this.machineId = machineId;
}
public int getMachineId() {
return this.machineId;
}
}
And then Outsourced:
package model;
public class Outsourced extends Part {
private String companyName;
public Outsourced(int id, String name, double price, int stock, int min, int max, String companyName) {
super(id, name, price, stock, min, max);
this.companyName = companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyName() {
return this.companyName;
}
}
If there is a particular part of Java you feel I need to brush up on to understand this, I am wide open to that. I want to understand the issue, not just get a fix. I'm not even looking for the answer, just a point in the direction of what the problem is.
Update
#Le and #Jackson pointed me in the right direction with their comments on the response he provided. I need to have a product first:
Product product = new Product(1, "test", 1.99, 1, 1, 1);
product.addAssociatedPart(selectedItem);
I was trying to explain you association of your various classes in comments but thought I would use visual help. I have simplified your scenario into a classic OOP problem.
public class Product {
public void addAssociatedPart(Part part) {
// some stuff
}
}
public abstract class Part {
}
public class InHouse extends Part {
}
public class Outsourced extends Part {
}
public class Assembly {
public static void main(String[] args) {
Product car = new Product();
Part seat = new InHouse();
Part engine = new Outsourced();
Part window = new InHouse();
car.addAssociatedPart(seat);
car.addAssociatedPart(engine);
car.addAssociatedPart(window);
}
}
I do not have any method in my Part or its sub-classes to add themselves to some Product. Was this you trying to achieve?
I am working on my AddProductController, trying to make a call to the
method in the Product class addAssociatedPart().
My problem is the compiler doesn't find the method in Part.
Why should it? Is Part a child of Product? Otherwise, you are calling a Product Method using a Part instance.
To use the methods of Inhouse and Oursourced for parts, you can do something like this
if (selectedItem instanceof InHouse){
Inhouse inhouse = (Inhouse)selectedItem;
//do what you need with inhouse methods
}else{
Outsourced outsourced = (Outsourced)selectedItem;
//do what you need with oursourced method
}
You are confused with static and non static method. You need a Product instance to access AddAssociatedPart(). Visualize your class in class diagram.
public void onAddProductAddPart(ActionEvent event) {
// this is triggered when the Add button is clicked
Part selectedItem = addProductTableViewAll.getSelectionModel().getSelectedItem();
selectedItem.addAssociatedPart(); // addAssociatedPart() is method of Product, not Part
Product.selectedItem.addAssociatedPart(); // Product class has no static member selectedItem
selectedItem.Product.addAssociatedPart(); // syntax error
addAssociatedPart(selectedItem); // addAssociatedPart() is not method of AddProcutController
Product.addAssociatedPart(selectedItem); // if you reference the method start with a class, the method is expected to be a static method. addAssociatedPart() is not a static method, call it with a product instance
InHouse newPart = new InHouse(1, "test", 1.99, 1, 1, 1, 101);
addAssociatedPart(newPart); // addAssociatedPart() is not part of AddProductController
Product.addAssociatedPart(newPart); // dont reference non-static method with a class name
newPart.addAssociatedPart(); // addAssociatedPart() is not part of Part
addProductTableViewPartial.setItems(associatedParts);
}
I am using a copy constructor and Inheritance in a class called 'Department' to call the information from class 'Teacher' which is a sub-class of 'Person'. After creating my set/get methods, I get the above error. Anyone have any insight as to why this is occurring?
Code from 'Department' class:
public class Department {
private String deptName;
private int numMajors;
private Teacher[] listTeachers; //inherits from Person class
private Student[] listStudents; //inherits from Person class
// First constructor for Department
public Department(String dn, int nm, Teacher[] listTeachers, Student[] listStudents) {
this.deptName = dn;
this.numMajors = nm;
this.listTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < this.listTeachers.length; i++)
{
this.listTeachers[i] = new Teacher (listTeachers[i]);
}
//set method for Teachers Array
public void setListTeachers (Teacher[] other) {
this.listTeachers = new Teacher[other.length];
for (int i = 0; i < listTeachers.length; i++) {
this.listTeachers[i] = new Teacher (other[i]);
}
}
//get method for Teachers Array
public Teacher[] getListTeachers() {
Teacher[] copyTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < copyTeachers.length; i++) {
copyTeachers[i] = new Teacher(this.listTeachers[i]);
}
return copyTeachers;
}
Here are the lines giving me errors:
1) this.listTeachers[i] = new Teacher (listTeachers[i]);
2) this.listTeachers[i] = new Teacher (other[i]);
3) copyTeachers[i] = new Teacher(this.listTeachers[i]);
Code from 'Teacher' class:
public class Teacher extends Person {
private String id;
private int salary;
private int num_yr_prof;
//Constructor for use in Teacher main method.
public Teacher(String n, int a, String s, boolean al, String i, int sal, int numyr) {
super(n, a, s, al);
this.id = i;
this.salary = sal;
this.num_yr_prof = numyr;
}
//Copy constructor for use in Department class.
public Teacher (String n, int a, String s, boolean al, Teacher other) {
super(n, a, s, al);
if (other == null) {
System.out.println("Fatal Error!");
System.exit(0);
}
this.id = other.id;
this.salary = other.salary;
this.num_yr_prof = other.num_yr_prof;
}
Your copy constructor might look like this:
public Teacher(Teacher teacher) {
this( teacher.n, teacher.a, teacher.s, teacher.al,
teacher.id, teacher.salary, teacher.num_yr_prof );
}
Since you do not show the code for the Person class, I have used the variable names n, a, s, and al here. They should be replaced by whatever those variables are named in the Person class. This, of course, assumes that those variables are either public or protected. If they are private, you need to use the getters for those variables (preferred even if they are public or protected).
You need to to your Teacher class a constructor that accepts a Teacher:
public Teacher(Teacher teacher) {
// do something
}
These are two classes of code that I wrote.. the problem here is I am not sure how to define class fields to represent Grass, fire and water as a Type using static..
Also I am not sure if I had used the super function the right way.. How do I properly call the parent's constructor so that I dont have to re define "knockedOut boolean" and be able to use Fire as the type?
Question could be confusing but I am not sure how to explain it better :( sorry
public abstract class Pokemon {
private String name;
private String type;
private int attack;
private int health;
private boolean knockedOut;
static private String Grass;
static private String Water;
static private String Fire;
public Pokemon (String n, String t, int a, int h) {
name = n;//state
type = t;//state
attack = a;//state
health = h;//state
knockedOut = false;
}
public abstract int takeDamage(Pokemon enemy);
public String toString() {
return "}";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public boolean isKnockedOut() {
return knockedOut;
}
public void setKnockedOut(boolean knockedOut) {
this.knockedOut = knockedOut;
}
}
public abstract class Charizard extends Pokemon {
private static String Fire;
private int attackFire;
private int healthFire;
private static String Water;
private static String Grass;
public Charizard(int a, int h) {
super("Charizard", Fire, a, h);
attackFire = a;
healthFire = h;
}
public int takeDamage(Pokemon enemy){
int enemyAttack = enemy.getAttack();
if(enemy.getType().equals(Water)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()*2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
}
else if(enemy.getType().equals(Fire)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()*2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
}
else if(enemy.getType().equals(Grass)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()/2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
if(healthFire <=0){
Charizard.set = true;
}
}
return enemyAttack;
}
}
You want to declare your different types like this:
static public final String GRASS= "Grass";
static public final String WATER = "Water";
static public final String FIRE = "Fire";
(I'm following the established convention here that fields declared static, public, and final should have names in all uppercase letters.)
By declaring these fields public, any other classes (including those that extend Pokemon, such as Charizard) that might need to test the type of a Pokemon can use them. By declaring them final, nobody can change them even though they are public. By giving them initial values, you make them actually useful for distinguishing different types of Pokemon, as well as avoid the inevitable NullPointerException that would happen the first time you executed something like p.getType().equals(Pokemon.FIRE)
As for knockedOut, it looks like you're handling it the right way. The field knockedOut is private in Pokemon but you've provided public getter and setter methods that other classes can (and do) use to access it.
Human has String named mName which is used in constructor, and Bicycle has String mOwner, I need to link one to another, Im new in this (programming) so Im not sure about what I should read about to understand better.
I created findOwner method that returns me mOwner, and declared mName "Dave" in Human's constructor... can I somehow make findOwner method return me current Human object's value?
sorry for my English and thank you)
Here's my code:
public class Human {
public String mName;
public Human(String name){
mName = name;
}
}
/* this one is my Bicycle */
public class Hecaniv {
private String mOwner;
private int mSpeed;
private int mShift;
private int mWheels;
public Hecaniv(int shift, int speed, int wheels){
mSpeed = speed;
mShift = shift;
mWheels = wheels;
}
public int currentSpeed(){
return mSpeed;
}
public int currentShift(){
return mShift;
}
public int numOfWheels(){
return mWheels;
}
public String findOwner(){
return mOwner;
}
}
Instead of having the name of the owner, you can just have the owner object itself as a field of Bicycle.
class Human {...}
class Bicycle {
Human owner;
public Bicycle(Human owner) {
this.owner = owner;
}
public Human findOwner() {
return owner;
}
}
I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}