Subclasses and Superclasses - java

I'm trying to build a program that has certain requirements, the main being I have a class, and then make a subclass that adds a feature. I create the class DVD, and then I create the subclass.
I'm adding a method to add the year to the list, as well as a restocking fee which will be added to the final inventory value that prints. I built the subclass, created the overriding methods, but it is not being added to the output displayed. Not only that, but it is placing the input year in the wrong place. I am not getting any errors, it just acts like the subclass doesn't exist, even though my DVD class says that some of the methods are being overridden.
I'm thinking I must be missing something where I am supposed to call the new method, and maybe I read the resource wrong, but it sounded like I only needed to call the DVD class, and the methods I wanted overridden would be overridden automatically. I'd prefer to just add this information to the superclass, but it is a requirement for an assignment.
So I'm wondering how do I actually go about calling these override methods when I need them to add these new features? I keep seeing resources telling me how to create them, but not actually implement them.
From my main method, I call the dvd class and then print it. however, it only prints what's in the original dvd class, except for the odd addition of adding the year to where the product ID should be.
public class DVD {
String name;
int id;
int items;
double cost;
//default constructor
public DVD() {
name = "";
id = 0;
items = 0;
cost = 0.0;
}//end default constructor
//constructor to initialize object
public DVD(String dvdName, int itemNum, int quantity, double price) {
name = dvdName;
id = itemNum;
items = quantity;
cost = price;
}//end constructor
//method to calculate value
public double getInventoryValue() {
return items * cost;
}
//method to set name
public void setdvdName(String dvdName){
this.name = dvdName;
}
//method to get name
public String getName(){
return name;
}
//method to set id
public void setitemNum( int itemNum){
this.id = itemNum;
}
//method to get id
public int getId(){
return id;
}
//method to set items
public void setquantity(int quantity){
this.items = quantity;
}
//method to get items
public int getItems(){
return items;
}
//method to set cost
public void setprice( double price){
this.cost = price;
}
//method to get cost
public double getCost(){
return cost;
}
/**
*
* #return
*/
public String toString() {
return "DVD Name: " + getName() +
"ID: " + getId() +
"Items: " + getItems() +
"Cost: " + getCost() +
"Total Value: " +getInventoryValue();
}
}
-
public class ExtendedDVD extends DVD{
double restockFee;
int year;
public ExtendedDVD(){
year = 0;
}
public ExtendedDVD(int year) {
this.year = year;
}
public void setRestockFee(){
this.restockFee = 0.05;
}
public double getRestockFee(){
return restockFee;
}
public void setYear(){
this.year = 0;
}
public int getYear(){
return year;
}
#Override
public double getInventoryValue(){
double value1 = super.getInventoryValue();
double value = restockFee * value1;
double totalInventoryValue = value + super.getInventoryValue();
return totalInventoryValue;
}
#Override
public String toString(){
return super.toString() + "Year" + getYear();
}
}
}
public class Inventory {
DVD[] inventory = new DVD[5];
int current = 0;
private int len;
public Inventory(int len){
inventory = new DVD[len];
}
public double calculateTotalInventory() {
double totalValue = 0;
for ( int j = 0; j < inventory.length; j++ )
totalValue += inventory[j].getInventoryValue();
return totalValue;
}
/**
*
* #param dvd
* #throws Exception
*/
public void addDVD(DVD dvd) throws Exception {
if (current < inventory.length) {
inventory[current++]=dvd;
}else {
Exception myException = new Exception();
throw myException;
}
}
void sort() {
for (DVD inventory1 : inventory) {
len = current;
}
for (int i=0; i<len;i++) {
for(int j=i;j<len;j++) {
if (inventory[i].getName().compareTo(inventory[j].getName())>0) {
DVD temp = inventory[j];
inventory[j] = inventory[i];
inventory[i] = temp;
}
}
}
}
public int getNumberOfItems() {
return current;
}
public void printInventory() {
System.out.println("Current Inventory:");
for(int i=0;i<current;i++) {
System.out.println(inventory[i]);
}
System.out.println("The total value of the inventory is:"+calculateTotalInventory());
}
}
-
public class inventoryprogram1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
boolean finish = false;
String dvdName;
int itemNum;
int quantity;
double price;
int year = 0;
Inventory inventory = new Inventory(5);
while (!finish) {
Scanner input = new Scanner(System.in); // Initialize the scanner
System.out.print("Please enter name of DVD: ");
dvdName = input.nextLine();
if (dvdName.equals("stop")) {
System.out.println("Exiting Program");
break;
} else {
System.out.print("Please enter Product Number: ");
itemNum = input.nextInt();
System.out.print("Please enter units: ");
quantity = input.nextInt();
System.out.print("Please enter price of DVD: ");
price = input.nextDouble();
System.out.print("Please enter production year: ");
itemNum = input.nextInt();
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
try {
inventory.addDVD(dvd);
}catch( Exception e) {
System.out.println("Inventory is full.");
break;
}
System.out.println("DVD: " + dvd);
}//end else
}
inventory.sort();
inventory.printInventory();
}
}

if you want to use the new methods that you wrote in ExtendedDVD you need to instantiate that class you are still calling the original dvd class so you will still get those methods.
for example
DVD dvd = new DVD(dvdName, itemNum, quantity, price);
and
DVD Dvd = new ExtendedDVD(dvdName, itemNum, quantity, price);
are two different things
also if you look in your main method you are assigning itemNum twice that is why it is showing you the year

In the main method you just instantiate a DVD object, not an ExtendedDVD object.
replace
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
by something like
DVD dvd= new ExtendedDVD(year);
And obviously, you may want another constructor in ExtendedDVD

Related

Pet BAG Assignment(Class file in Java)-Cannot run the program in Eclipse IDE through apporto

The image is the error message i get as well as showing the eclipse IDEThe problem I am having is I cant get my code to run through the eclipse IDE each time I click run it doesn't run and just gives me an error message "The selection cannot be launched, and there are no recent launches." I am trying to create a PET class file through java.
here is the code for my assignment:
import java.util.Scanner;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
public class Pet {
private String petType;
private String petName;
private int petAge;
private Map<Pet, Integer> dogSpace; // contains the Pet and days it is staying
private Map<Pet, Integer> catSpace; // same but for cats
private int daysStay;
public double amountDue;
/**
* Pet, base class for Dog and Cat
* #param String name - Name of the Pet
* #param int age - Age of the Pet
* #param String type - Cat | Dog
*/
public Pet(String name, int age, String type) {
this.petName = name;
this.petAge = age;
this.petType = type;
this.dogSpace = new HashMap<Pet, Integer>(); // use a hashmap to keep track of pets in the shelter
this.catSpace = new HashMap<Pet, Integer>(); // the Pet object is the key, and the days they are staying is the value.
}
public void checkIn(Pet pet) {
Scanner in = new Scanner(System.in);
System.out.println("How many days will your " + this.petType + " be staying?");
int days = (int) in.nextInt();
this.daysStay = days;
switch(this.petType) {
case "Dog":
if(days > 1) {
System.out.println("Do you require grooming services?");
String needsGrooming = in.next();
boolean grooming;
if(needsGrooming.equals("yes") || needsGrooming.equals("y")) {
System.out.println("We will groom your dog...\n");
grooming = true;
}
else {
grooming = false;
}
this.checkInDog((Dog) pet, days, grooming); // handle the special dog cases
}
else {
this.checkInDog((Dog) pet, days, false);
}
break;
case "Cat":
if(this.catSpace.size() < 12) {
this.catSpace.put(pet, days);
}
break;
default: // Throw an exception if a pet other than a Cat | Dog is booked.
in.close(); // Close the scanner before exiting.
throw new RuntimeException("Sorry, we only accept cats and dogs");
}
in.close(); // Close the scanner when there is no exceptin thrown.
}
/**
* Contains extra steps for checking in a dog.
* #param pet - The dog object.
* #param days - Number of days staying.
* #param grooming - Whether or not the dog needs grooming.
*/
private void checkInDog(Dog pet, int days, boolean grooming) {
pet.setGrooming(grooming);
try {
if(this.dogSpace.size() < 30) { // Enforce the maximum of 30 dogs in the shelter.
this.dogSpace.put(pet, days);
pet.dogSpaceNbr = this.dogSpace.size() + 1;
pet.setDaysStay(days);
}
}
catch (Exception e) { // For some Map objects, calling size() on an empty collection can throw an error.
System.out.println("You're our first visitor!");
System.out.print(pet);
this.dogSpace.put(pet, days);
pet.dogSpaceNbr = 1;
}
System.out.println("" + pet.getPetName() + " will miss you, but is in good hands.");
}
/**
* Check out the desired Pet and calculate how much is owed for the boarding.
* #param pet - The pet you wish the check-out.
* #return amountDue - The amount of money owed for the boarding.
*/
public double checkOut(Pet pet) {
double fee;
if(pet.getPetType() == "Dog") {
double groomingfee = 0.0;
Dog animal = (Dog) pet;
int days = this.dogSpace.remove(pet);
double weight = animal.getDogWeight();
if(weight < 20) {
fee = 24.00;
if(animal.getGrooming()) {
groomingfee = 19.95;
}
} else if (weight > 20 && weight < 30) {
fee = 29.00;
if(animal.getGrooming()) {
groomingfee = 24.95;
}
} else {
fee = 34.00;
if(animal.getGrooming()) {
groomingfee = 29.95;
}
}
System.out.println("Fee Schedule:\n Boarding Fee: " + (fee*days) + "\nGrooming Fee: " + groomingfee);
animal.amountDue = (fee * days) + groomingfee;
return animal.amountDue;
}
else {
int days = this.catSpace.remove(pet);
fee = 18.00;
pet.amountDue = (fee * days);
return pet.amountDue;
}
}
public Pet getPet(Pet pet) { // Not sure why we need this.
return pet;
}
public Pet createPet(String name, int age, String type) {
switch(type) {
case "Dog":
return new Dog(name, age);
case "Cat":
return new Pet(name, age, "Cat"); // I have implemented the dog class, not the cat.
default:
throw new Error("Only Dogs and Cats can stay at this facility.");
}
}
/**
* Asks the user to fill in all of the attributes of a pet. Saves them directly to the object it was called on.
* #param pet - The pet you wish to update information on.
*/
public void updatePet(Pet pet) {
Scanner in = new Scanner(System.in);
System.out.println("What is the pets new name?");
pet.setPetName(in.next());
System.out.println("What is the pets age?");
pet.setPetAge(in.nextInt());
System.out.println("What type of animal is your pet?");
pet.setPetType(in.next());
in.close();
}
public String getPetName() {
return this.petName;
}
public int getPetAge() {
return this.petAge;
}
public String getPetType() {
return this.petType;
}
public void setPetName(String name) {
this.petName = name;
}
public void setPetAge(int age) {
this.petAge = age;
}
public void setPetType(String type) {
switch(type) { // while a switch is extra here, it will make it easier to add other pets.
case "Dog":
this.petType = type;
break;
case "Cat":
this.petType = type;
break;
}
}
public void setDaysStay(int days) {
this.daysStay = days;
}
}
public class Dog extends Pet {
public int dogSpaceNbr;
private double dogWeight;
private boolean grooming;
public Dog(String name, int age) { // automatically declares a pet of type Dog
super(name, age, "Dog"); // super is used to call the parent classes constructor
}
public double getDogWeight() {
return this.dogWeight;
}
public boolean getGrooming() {
return this.grooming;
}
public void setDogWeight(double weight) {
this.dogWeight = (double) weight; // casting a double here might be redundant, but it helps us to be sure
} // we don't get at type error
public void setGrooming(boolean value) {
this.grooming = value;
}
}
public class Cat extends Pet {
private int catSpaceNbr; // The number space the cat is in.
public Cat(String name, int age) { // automatically declares a pet of type Cat
super(name, age, "Cat"); // Calls the constructor of the parent class
}
public int getCatSpace() {
return this.catSpaceNbr;
}
public void setCatSpace(int number) {
this.catSpaceNbr = number;
}
}type here
I haven't tried much to fix the issue besides look up videos and now reach out for help just not sure what to do.
In the Package Exporer or Navigator tab (right hand panel) right-click on the class that contains public static void main and choose Run as >> Java application.
When you have done that successfully you can run with the run button.

How to Correctly Call Item2.calculateUnitTotal() so I Can Add Amount to a Total Variable [duplicate]

This question already has answers here:
"Non-static method cannot be referenced from a static context" error
(4 answers)
Closed 3 years ago.
Alright! So I'm still new to Java and we just started learning about Instances and classes this week.
My problem is that my professor assigned a program (that I've already spent around 10 hours on, I've made headway but I'm still having problems) that has slightly vague instructions, and I'm not sure how to incorporate them into my program.
It's a shopping cart program that takes the name, description, price, and quantity of a product. All of these qualities go into the Item2 class, which I'm not having problems with, and then print using the toString() method in the Item2 class.
Next, I take the name and add this to an array in the ShoppingCart2 class (addItems method), and then make the getTotal method that will go through arrayItems, and add up prices of each item (should call calculateUnitTotal() method of each Item object and add up).
My problem is that by trying to call calculateUnitTotal(), I am either getting the error:
non static method cannot be referenced from a static context
or the dereference error.
My professor does not want me to call the units and price objects from the Item2 class, I need to call this method specifically.
I know that I need to create an instance to do this, and that an object can't be converted to a double, but everything I try doesn't seem to work.
I'm not sure what I'm doing wrong. I also know that the code is kinda messy, I tried my best to clean it up. Any advice would be appreciated!
Item2.java:
class Item2{
private String productName;
public class Item2{
private String productName;
private String productDesc;
private double unitPrice;
private int units;
public String getProductName(){
return productName;
}
public String getproductDesc(){
return productDesc;
}
public double getUnitPrice(){
return unitPrice;
}
public int getUnits(){
return units;
}
public void setProductName(String newProductName){
productName = newProductName;
}
public void setProductDesc(String newProductDesc){
productDesc = newProductDesc;
}
public void setUnitPrice(double newUnitPrice){
unitPrice = newUnitPrice;
}
public void setUnits(int newUnits){
units = newUnits;
}
void Item2(){
productName = "";
productDesc = "";
unitPrice = -1;
units = -1;}
public void Item2(String newProductName, String newProductDesc,
double newUnitPrice, int newUnits) {
productName = newProductName;
productDesc = newProductDesc;
unitPrice = newUnitPrice;
units = newUnits;
}
public double calculateUnitTotal(){
double total = unitPrice * units;
return total;
}
public String toStrings() {
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return (productName + "\t" + fmt.format(unitPrice) + "\t" +
units + "\t" + fmt.format(unitPrice * units));
}
}
ShoppingCart2.java:
class ShoppingCart2{
private String[] arrayItems;
private int numItems;
public ShoppingCart2(){
arrayItems = new String[20];
numItems = 0;
}
public void addItems(String itemName){
for(int i = 0; i < numItems; i++){
if(numItems==arrayItems.length)
System.out.println("Cart is full.");
else{
arrayItems[numItems]= itemName;
numItems++;
}
}
}
public ShoppingCart2 getTotal(){
ShoppingCart2 total = new ShoppingCart2();
for(int i = 0; i < numItems; i++){
/////I've tried several different methods here, they always
////lead to either
/// a need to dereference or the non static method error
}
return total;}
public String toString() {
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String cart = "\nShopping Cart\n";
for (int i = 0; i < numItems; i++)
cart += arrayItems[i] + "\n";
cart += "\nTotal Price: " + fmt.format(total);
cart += "\n";
return cart;
}
}
I expect the output to be the names of the items in the array and the total of all the items.
It sounds to me that the idea is to use Item2 class to encapsulate all the properties, and then use ShoppingCart2 to administrate what do you with them.
So, your ShoppingCart2 may have to look like:
class ShoppingCart{
private ArrayList<Item2> items;
public ShoppingCart2(){
items = new ArrayList<Item2>();
}
public void addItem(Item2 item){
items.add(item);
}
public void addItems(ArrayList<Items> items){
this.items.addAll(items)
}
public double getTotal(){
double total = 0L;
for(Item2 item : items){
total += item.calculateUnitTotal();
}
return total;
}
public String toString(){
StringBuffer sb = new StringBuffer();
for (Item2 item: items){
// Print each item here
sb.append(item.toString());
sb.append("----------------\n");
}
sb.append("*************");
sb.append("Total Price: ");
sb.append(getTotal());
return sb.toString();
}
}
Note: this code wasn't fully tested.
* UPDATE *
A closer look shows that your Item2 class is wrong.
Here is a cleaner version.
class Item2 {
private String productName;
private String productDesc;
private double unitPrice;
private int units;
public Item2(){
productName = "";
productDesc = "";
unitPrice = -1;
units = -1;
}
public Item2(String newProductName,
String newProductDesc,
double newUnitPrice,
int newUnits) {
productName = newProductName;
productDesc = newProductDesc;
unitPrice = newUnitPrice;
units = newUnits;
}
public String getProductName(){
return productName;
}
public String getproductDesc(){
return productDesc;
}
public double getUnitPrice(){
return unitPrice;
}
public int getUnits(){
return units;
}
public void setProductName(String newProductName){
productName = newProductName;
}
public void setProductDesc(String newProductDesc){
productDesc = newProductDesc;
}
public void setUnitPrice(double newUnitPrice){
unitPrice = newUnitPrice;
}
public void setUnits(int newUnits){
units = newUnits;
}
public double calculateUnitTotal(){
return unitPrice * (double) units;
}
public String toString() {
NumberFormat fmt = NumberFormat.getCurrencyInstance();
StringJoiner sj = new StringJoiner("\t");
sj.add(productName).add(unitPrice).add(units).add(fmt.format(unitPrice * units));
return sj.toString();
}
}
Some Explanation
The reason you wish to use StringJoiner or StringBuffer when concatenating strings is that it way more efficient then using the plus sign + operator.
The plus operator create a lot of overhead since it takes two parameters, strings, and create a brand new string from them.
StringBuffer and StringJoiner allows you to add the strings and in the last moment, you can turn them all together into a string.

Creating a method and returning object

I am extremely stuck on this assignment I have, this is the last part of the assignment and it is going over my head. We were given this code to start off with.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
Employee e1 = new Employee2(7, "George Costanza");
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e1.displayEmployee();
//Employee e2 = createEmployeeFromFile();
//e2.displayEmployee();
}
}
We were told to create a method called createEmployeeFromFile();. In this method we are to read from a .txt file with a Scanner and use the data to create an Employee object. Now I am confused on two things. First on the method type I should be using, and how to create an object with the data from the .txt file. This is the first time we have done this and it is difficult for me. Employee1 works fine, but when trying to create my method I get stuck on what to create it as.
Here is my rough draft code for right now.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
EckEmployee2 e1 = new EckEmployee2(7, "George Costanza");
EckEmployee2 e2 = createEmployeeFromFile();
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e2.setNumber();
e2.setName();
e2.setDepartment();
e2.setPosition();
e2.setSalary();
e2.setRank();
e1.displayEmployee();
e2.displayEmployee();
}
createEmployeeFromFile(){
File myFile = new File("employee1.txt");
Scanner kb = new Scanner(myFile);
}
}
I am not expecting to get the answer just someone to point me in the right direction. Any help is greatly appreciated.
Here is my code from my main class.
public class EckEmployee2 {
private int rank;
private double number;
private double salary;
private String name;
private String department;
private String position;
public EckEmployee2() {
number = 0;
name = null;
department = null;
position = null;
salary = 0;
rank = 0;
}
public EckEmployee2(double number, String name) {
this.number = number;
this.name = name;
}
public EckEmployee2(double number, String name, String department, String position, double salary, int rank) {
this.number = number;
this.name = name;
this.department = department;
this.position = position;
this.salary = salary;
this.rank = rank;
}
public void setNumber(double num) {
this.number = num;
}
public double getNumber() {
return this.number;
}
public void setName(String nam) {
this.name = nam;
}
public String getName() {
return this.name;
}
public void setDepartment(String dept) {
this.department = dept;
}
public String getDepartment() {
return this.department;
}
public void setPosition(String pos) {
this.position = pos;
}
public String getPosition() {
return this.position;
}
public void setSalary(double sal) {
this.salary = sal;
}
public double getSalary() {
return this.salary;
}
public void setRank(int ran) {
this.rank = ran;
}
public int getRank() {
return this.rank;
}
public boolean checkBonus() {
boolean bonus = false;
if (rank < 5) {
bonus = false;
} else if (rank >= 5)
bonus = true;
return bonus;
}
public void displayEmployee() {
if (checkBonus() == true) {
System.out.println("-------------------------- ");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: \n" + department);
System.out.println("Position: \n" + position);
System.out.printf("Salary: %,.2\n" , salary);
System.out.println("Rank: \n" + rank);
System.out.printf("Bonus: $\n", 1000);
System.out.println("-------------------------- ");
} else if (checkBonus() == false)
System.out.println("--------------------------");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: " + department);
System.out.println("Position: " + position);
System.out.printf("Salary: %,.2f\n" , salary);
System.out.println("Rank: " + rank);
System.out.println("-------------------------- ");
}
}
To make things more clear here are the directions
Create a method in TestEmployee2 called createEmployeeFromFile() that will read data from a file and create, populate and return an Employee object. The file it will read from is called employee1.txt, which is provided. Hard code the name of the file in the method. This file contains the employee’s number, name, department, position, salary and rank. Create a Scanner object and use the Scanner class’s methods to read the data in the file and use this data to create the Employee object. Finally return the employee object.
In java, to return a value from a method, you add that objects type into the method signature as below, and in short java method signatures are as follows
'modifier (public, private, protected)' 'return type (void/nothing, int, long, Object, etc...' 'methodName(name the method)' 'parameters (any object or primitive as a parameter'
The method below will work if you have an employee contstructor which parses the input text, and assuming the data is split my a delimiter, you can use String.split(splitString); where splitString is the character that splits the data, i.e) a comma ",".
public EckEmployee2 getEmployee()
{
try
{
/**
* This will print where your java working directory is, when you run the file
*
*/
System.out.println(System.getProperty("user.dir"));
/**
* Gets the file
*/
File myFile = new File("employee1.txt");
/**
* Makes the scanner
*/
Scanner kb = new Scanner(myFile);
/**
* A list to store the data of the file into
*/
List<String> lines = new ArrayList<>();
/**
* Adds all the lines in the file to the list "lines"
*/
while (kb.hasNext())
{
lines.add(kb.next());
}
/**
* Now that you have the data from the file, assuming its one line here, you can parse the data to make
* your "Employee"
*/
if (lines.size() > 0)
{
final String line = lines.get(0);
return new EckEmployee2(line);
}
}
/**
* This is thrown if the file you are looking for is not found, it either doesn't exist or you are searching
* in the wrong directory.
*/
catch (FileNotFoundException e)
{
e.printStackTrace();
}
/**
* Return null if an exception is thrown or the file is empty
*/
return null;
}
First your method createEmployeeFromFile() must take 2 parameters, a Scanner object to read input, and the File you're gonna be reading from using the Scanner.
The return type is Empolyee2 because the method creates a Employee2 instance and must return it.
Now, I gave you the initiatives.
Your turn to read more about Scanner object and File object.
Reading from the text file, the attributes of your object, is easy then you create an instance by using the constructor with the attributes and return it!
Hope this helps.

how to use abstract classes, and implementing them

I'm not sure how eloquently I can really explain what I don't understand/need help with, I'm still Very new to Object Oriented Programming. This is regarding my coursework and I don't expect anyone to do it for me, I just need help understanding how to move on, and if I'm even on the right track.
Ok, so on to my question. Basically, I am attempting to create an arraylist which will hold a few objects which themselves has a bunch of information(obviously), my spec said to create an abstract class, which will be extended by my constructor class, which I did. The abstract class has a few variables (decided by spec) But I dont know how to move them over to my extended class.
I'll post my code below, and I hope it makes sense. I'd be very thankful for any help you all could provide. I'm very confused right now.
Basically, I would love to know, A) How do I create an object in my arraylist which will be able to contain everything in SportsClub and FootballClub, and preferably all the variables user inputted.
And B) I don't know how to print The object, When I print right now I get coursework.FootballClub#49233bdc, Which I'm sure there's a reason for but I need the information in the objects to display, E.g. name. And if possible to sort the results by alphabetical order with respect to name? I hope this is all written ok. Sorry and Thank you in advance.
package coursework;
import java.util.*;
/**
*
* #author w1469384
*/
public class PremierLeagueManager implements LeagueManager{
public static void main(String[] args) {
Scanner c1 = new Scanner(System.in);
Scanner c2 = new Scanner(System.in);
ArrayList<FootballClub> PL = new ArrayList<FootballClub>();
int choice;
System.out.println("Enter 1; To create a club, 2; To Delete a Club, 3; To display all clubs and 99 to close the program");
choice = c1.nextInt();
//Creates and adds a new FootballClub Object
while (choice != 99){
if (choice == 1){
System.out.println("Please Enter The games played for the club");
int played = c1.nextInt();
System.out.println("Please enter the number of wins");
int wins = c1.nextInt();
System.out.println("please enter the number of losses");
int losses = c1.nextInt();
System.out.println("please enter the number of draws");
int draws = c1.nextInt();
System.out.println("please enter the number of goals for");
int goalsFor = c1.nextInt();
System.out.println("please enter the number of goals against");
int goalsAgainst = c1.nextInt();
FootballClub club = new FootballClub(played, wins, losses, draws, goalsFor, goalsAgainst);
PL.add(club);
System.out.println("check");
}
//Deletes a FootballClub Object
if (choice == 2){
}
//Displays all Football Clubs in the PremierLeague array
if (choice == 3){
System.out.println(PL);
}
//Closes the Program 1
choice = c1.nextInt();
}
}
}
public abstract class SportsClub {
public String name;
public String location;
public int capacity;
public void setName(String Name){
name = Name;
}
public void setLocation(String Location){
location = Location;
}
public void setCapacity(int Capacity){
capacity = Capacity;
}
public String getName(){
return name;
}
public String getLocation(){
return location;
}
public int getCapacity(){
return capacity;
}
}
public class FootballClub extends SportsClub {
//Statistics for the club.
int played;
int wins;
int losses;
int draws;
int goalsFor;
int goalsAgainst;
public FootballClub(int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst){
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
public void setPlayed(int newPlayed){
played = newPlayed;
}
public void setWins(int newWins){
wins = newWins;
}
public void setLosses(int newLosses){
losses = newLosses;
}
public void setDraws(int newDraws){
draws = newDraws;
}
public void setGoalsFor(int newGoalsFor){
goalsFor = newGoalsFor;
}
public void setGoalsAgainst(int newGoalsAgainst){
goalsAgainst = newGoalsAgainst;
}
public int getPlayed(){
return played;
}
public int getWins(){
return wins;
}
public int getLosses(){
return losses;
}
public int getDraws(){
return draws;
}
public int getGoalsFor(){
return goalsFor;
}
public int getGoalsAgainst(){
return goalsAgainst;
}
}
FootballClub inherits the variables declared in SportsClub so you can set them as you please.
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
// set the variables from the superclass
name = inName;
location = inLocation;
capacity = inCapacity;
}
FootballClub also inherits the methods declared in SportsClub so you can use the setters and getters too.
Normally you would create a constructor for SportsClub that sets these and then call that constructor from the FootballClub constructor.
// in SportsClub
protected SportsClub(
String inName, String inLocation, int inCapacity
) {
name = inName;
location = inLocation;
capacity = inCapacity;
}
// in FootballClub
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
super(inName, inLocation, inCapacity);
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
You should also make your member variables protected or private if you are using setters and getters.
I don't know how to print The object
You need to override toString. There is a short tutorial here.
Also unrelated side note: all Java variable identifiers should start with a lowercase letter.
When you have a method like this:
public void setName(String Name) { name = Name; }
It should be:
public void setName(String inName) { name = inName; }
Or:
public void setName(String name){ this.name = name; }

java Error Message: Missing Method Body Or Declare Abstract, how to fix this?

hello I get the error message: Missing Method Body Or Declare Abstract, how to fix this, what does this mean?
my code:
public class Mobile
{
// type of phone
private String phonetype;
// size of screen in inches
private int screensize;
// memory card capacity
private int memorycardcapacity;
// name of present service provider
private String mobileServiceProvider;
// type of contract with service provider
private int mobileTypeOfContract;
// camera resolution in megapixels
private int cameraresolution;
// the percentage of charge left on the phone
private int chargeUp;
// wether the phone has GPS or not
private int switchedOnFor;
// to simulate using phone for a period of time
private int charge;
// checks the phones remaining charge
private String provider;
// simulates changing the provider
private String GPS;
// instance variables - replace the example below with your own
private int cost;
// declares cost of the item
// The constructor method
public Mobile(String mobilephonetype, int mobilescreensize,
int mobilememorycardcapacity, String mobileServiceProvider, int mobileTypeOfContract, int mobilecameraresolution, String mobileGPS, int chargeUp,int switchedOnFor, String changeProvider,int getBalance, int cost,int price) {
// initialise the class attributes from the one given as parameters in your constructor.
}
/**
* Other constructor
*/
public Mobile (int cost){
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
/**
*returns a field price.
*/
public int getcost()
{
return balance;
}
/**
*return the amount of change due for orders of mobiles.
*/
public int getBalance()
{
return balance;
}
/**
* Receive an amount of money from a customer.
*/
public void cost (int price)
{
balance = balance + amount;
}
//this.serviceprovider = newserviceprovider;
//this.typeofcontract = 12;
//this.checkcharge = checkcharge;
//this.changeProvider = giffgaff;
//Mobile samsungPhone = new Mobile(
// "Samsung" // String mobilephonetype
//, 1024 // intmobilescreensize
//, 2 // intmobilememorycardcapacity
//, 8 // intmobilecameraresolution
//, "GPS" //String mobileGPS
//, "verizon" // String newserviceprovider
//, "100" // intchargeUp
//, "25" // intswitchedOnFor
//, "25" // intcheckCharge
//, "giffgaff"// String changeProvider
//);
//typeofcontract = 12;
//checkcharge = checkcharge;
//Mutator for newserviceprovider
public void setmobileServiceProvider(String newmobileServiceProvider)
{
mobileServiceProvider = newmobileServiceProvider;
}
//Mutator for contracttype
public void setmobileTypeOfContract(int newmobileTypeOfContract)
{
mobileTypeOfContract = newmobileTypeOfContract;
}
//Mutator for chargeUp
public void setchargeUp(int chargeUp)
{
this.chargeUp = chargeUp;
}
//Mutator to simulate using phone for a period of time
public void switchedOnFor(int switchedOnFor)
{
this.switchedOnFor = switchedOnFor;
}
//Accessor for type of phone
public String getType()
{
return phonetype;
}
//Accessor for provider
public String getprovider()
{
return mobileServiceProvider;
}
//Accessor for contract type
public int getContractType()
{
return mobileTypeOfContract;
}
//Accessor for charge
public int getCharge()
{
return chargeUp;
}
//Accessor which checks the phones remaining charge
public int checkCharge()
{
return checkCharge;
}
// simulates changing the provider
public void changeProvider()
{
provider = changeProvider;
}
//returns the amount of change due for orders of mobiles.
public int Balance()
{
return balance;
}
// A method to display the state of the object to the screen
public void displayMobileDetails() {
System.out.println("phonetype: " + phonetype);
System.out.println("screensize: " + screensize);
System.out.println("memorycardcapacity: " + memorycardcapacity);
System.out.println("cameraresolution: " + cameraresolution);
System.out.println("GPS: " + GPS);
System.out.println("mobileServiceProvider: " + mobileServiceProvider);
System.out.println("mobileTypeOfContract: " + mobileTypeOfContract );
}
/**
* The mymobile class implements an application that
* simply displays "new Mobile!" to the standard output.
*/
public class mymobile {
public void main(String[] args) {
System.out.println("new Mobile!"); //Display the string.
}
}
public static void buildPhones(){
Mobile Samsung = new Mobile("Samsung",3,4,"verizon",8,12,"GPS",100,25,"giffgaff");
Mobile Blackberry = new Mobile("Samsung",3,4,"verizon",8,12,"GPS",100,25,"giffgaff");
}
public static void main(String[] args) {
buildPhones();
}
}
any answers or replies and help would be greatly appreciated as I cant get it to compile like it did before with no syntax errors.
Check constructor declared on line 42. It doesn't have a body.
public Mobile (int cost); {
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
Additionally, price and a number of other fields are not declared anywhere.
remove ; from
public Mobile (int cost); {
public Mobile (int cost); {
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
Here, you left a semicolon, delete it.
public Mobile (int cost){
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}

Categories

Resources