having hard time calling a method in the main. keeps saying that it cannot find symbol - method addSales(double)
i am doing a project for programming because we just learnt about inheritance and it has 3 super classes and 3 sub classes. i am having a problem with one sub and super class. they are named Hourly and Commission. commission extends hourly. i feel like i have written the method called addSales correctly however when i call it in the main it says that it cannot find the method. am i missing something here? any help would be greatly appreciated.
Commission class:
public class Commission extends Hourly
{
private double totalSales, commission;
public Commission(String eName, String eAddress, String ePhone,
String socSecNumber, double rate, double commissionRate)
{
super(eName, eAddress, ePhone, socSecNumber, rate);
totalSales = 0.0;
commission = commissionRate;
}
public double pay()
{
double payment = super.pay();
payment = (payment + (commission * totalSales));
return payment;
}
public String toString()
{
String result = super.toString();
result += "Total Sales: " + totalSales;
return result;
}
public void addSales(double totalS)
{
totalSales = totalSales + totalS;
}
}
Hourly class:
public class Hourly extends Employee
{
private int hoursWorked;
//-----------------------------------------------------------------
// Sets up this hourly employee using the specified information.
//-----------------------------------------------------------------
public Hourly (String eName, String eAddress, String ePhone,
String socSecNumber, double rate)
{
super (eName, eAddress, ePhone, socSecNumber, rate);
hoursWorked = 0;
}
//-----------------------------------------------------------------
// Adds the specified number of hours to this employee's
// accumulated hours.
//-----------------------------------------------------------------
public void addHours (int moreHours)
{
hoursWorked += moreHours;
}
//-----------------------------------------------------------------
// Computes and returns the pay for this hourly employee.
//-----------------------------------------------------------------
public double pay()
{
double payment = payRate * hoursWorked;
hoursWorked = 0;
return payment;
}
//-----------------------------------------------------------------
// Returns information about this hourly employee as a string.
//-----------------------------------------------------------------
public String toString()
{
String result = super.toString();
result += "\nCurrent hours: " + hoursWorked;
return result;
}
}
main:
public class Firm
{
//--------------------------------------------------------------
// Creates a staff of employees for a firm and pays them.
//--------------------------------------------------------------
public static void main (String[] args)
{
Staff personnel = new Staff(8);
Executive staff0 = new Executive ("Sam", "123 Main Line", "555-0469", "123-45- 6789", 2423.07);
StaffMember staff1 = new Employee ("Carla", "456 Off Line", "555-0101", "987-65-4321", 1246.15);
StaffMember staff2 = new Employee ("Woody", "789 Off Rocker", "555-0000", "010-20-3040", 1169.23);
Hourly staff3 = new Hourly ("Diane", "678 Fifth Ave.", "555-0690", "958-47-3625", 10.55);
Hourly staff6 = new Commission("Marcus Gendron", "66 Highland St.", "272-9555", "123-62-5678", 6.25, 0.20);
Hourly staff7 = new Commission("Joe Dangerous", "55 dude Court", "555-1267", "777-66-5555", 9.75, 0.15);
StaffMember staff4 = new Volunteer ("Norm", "987 Suds Blvd.", "555-8374") ;
StaffMember staff5 = new Volunteer ("Cliff", "321 Duds Lane", "555-7282");
personnel.addStaff(staff0);
personnel.addStaff(staff1);
personnel.addStaff(staff2);
personnel.addStaff(staff3);
personnel.addStaff(staff4);
personnel.addStaff(staff5);
personnel.addStaff(staff6);
personnel.addStaff(staff7);
staff6.addHours(35);
staff6.addSales(400.0);
//error is being shown here ^^^^
staff7.addHours(40);
staff7.addSales(950.00);
staff0.awardBonus (500.00);
staff3.addHours (40);
personnel.payday();
}
}
Both staff6 and staff7 are instances of Hourly. The Hourly class does not have that particular method attached to it.
You would have to declare them as concrete instances of Commission instead.
staff6 is declared as Hourly, and even though it is in fact a Commission, you are trying to access the super class' method.
Declare it as Commission.
I see the object creation below:
Hourly staff6 = new Commission("Marcus Gendron", "66 Highland St.", "272-9555", "123-62-5678", 6.25, 0.20);
addSales method is in the child class Commission. But the type of staff6 is Hourly which is the parent class and Hourly class doesnt have this method. This you dont see the method addsales.
For more detailed understanding, try the following line (which will compile fine). And see what all methods you get
Object staff6 = new Commission("Marcus Gendron", "66 Highland St.", "272-9555", "123-62-5678", 6.25, 0.20);
Here You can only able to call methods that are present on Hourly class.
Because You are referencing Hourly class now as addSales in not present on Hourly class it is not accessible.
Hourly staff6 = new Commission("Marcus Gendron", "66 Highland St.", "272-9555", "123-62-5678", 6.25, 0.20);
In your above code Commission class object have reference to Hourly class. So Commission object will only allowed to access those methods which are Hourly class ( because they are inherited ) and overridden methods of hourly class in commission class.
Related
I have a school project I am working on, I am a beginner at java and have started to learn abstract classes. As of right now, I have covered inheritence and interfaces and my teacher has provided me with some source code. The main goal of the project is to create an invoice of a group of objects from subclasses part of other subclasses that are part of one superclass. The invoice has to have the summary of the objects (its name, cost, and flavour/seats) along with the total price, its tax and grand total that is to be printed using a method called getDescription() that is overwritten for each sub class. Keep in mind that some 'objects' have a luxury tax involved that is 15% and there is a total 8% sales tax also added. The invoice (with luxury tax already added) is supposed to look like this:
Chocolate Croissant $1.99
Evinrude 5-seat motorboat $3,475.00
Oceano 12-cabin yacht $1,045,000.00 ** Luxury tax added **
Beluga caviar from Caspian Sea $655.50 ** Luxury tax added **
Total price: $1,049,132.49
Tax : $83,930.60
Grand total: $1,133,063.09
However, I am getting two problems when I try this, first, the numbers I have (the seperate costs with the luxury tax), aren't adding up to the total price because I am not able to add the objects separate prices together as I have declared that in the parameters, and not as separate variables inside the main class itself, and so I cannot call on the method that lets me calculate the luxury tax before calculating for the total cost.
The second problem I have is not being able to put the correct decimal points for the price output, my teacher has provide a toString method in the superclass but I am not sure how to use it since, again, the cost itself is in the parameters of the object and not as an object or variable itself. This is not as big of a priority however, so it's alright if a solution for this is not provided.
Here is my Item superclass code, only part of it for context, and the part of my Boat subclass, and it's two 'Motorboat' and 'Yacht' subclasses. Yacht subclass also implements an interface class called LuxuryItem which only has one abstract method called 'calculateLuxuryTax' that we overwrite for each of the subclasses, which is why I won't provide that. Along with that, there is also the main class that has the object creation for each of the four subclass (Caviar, Pastry, Yacht, Motorboat) and in the constructors there are the same general format of the parameters (name, cost, horsepower/calories, flavour/origin/cabin #/seat #)
Item Class
import java.text.NumberFormat; //do I have to import this to each sub class? is that why there are no two decimal places for each output??
abstract class Item {
double cost;
String name;
public Item() {
cost = 0.0;
name = "";
}
public Item(String name, double cost) {
this.name = name;
this.cost = cost;
}
// a set cost method is also here, just not including it
public double getCost() {
return this.cost;
}
//over here, i have deleted are getters and setters for name property
public String toString() {
NumberFormat currency = NumberFormat.getCurrencyInstance();
String result;
result = name + " -- Cost: " + currency.format(cost);
return result;
}
public String getDescription() {
return this.name;
}
}
Boat Subclass & Motorboat and Yacht subclasses of Boat subclass
//all three classes are in one file
abstract class Boat extends Item {
//boat class with state variable
int horsepower;
public Boat(String name, double cost, int horsepower) {
super(name, cost);
this.horsepower = horsepower;
} //constructor that calls everything
public int getHorsepower() {
return this.horsepower;
}
public void setHorsepower(int horsepower) {
this.horsepower = horsepower;
}
public String toString() {
return super.toString() + " Horsepower: " + horsepower;
}
}
class Motorboat extends Boat {
int seats;
public Motorboat(String name, double cost, int horsepower, int seats) {
super(name, cost, horsepower);
this.seats = seats;
}
public String getDescription() {
String description = (name + " " + seats + "-seat motorboat $" + cost);
System.out.println(description);
return description;
}
public void setSeats(int seats) {
this.seats = seats;
}
public int getSeats() {
System.out.println("The amount of seats in the motoboat is " + seats);
return seats;
}
}
class Yacht extends Boat implements LuxuryItem {
int cabins;
public Yacht(String name, double cost, int horsepower, int cabins) {
super(name, cost, horsepower);
this.cabins = cabins;
}
public void setCabins(int cabins) {
this.cabins = cabins;
}
public int getCabins() {
System.out.println("The people with cabins in the yacht are " + cabins);
return cabins;
}
public double calculateLuxuryTax() {
final double tax = 0.10;
double luxuryTax = (cost*tax);
return luxuryTax;
}
public String getDescription() {
String description = (name + " " + cabins + "-cabin yacht $" + cost + " ** Luxury tax added **");
System.out.println(description);
return description;
}
}
Main class where my objects are created in the main method
class Main {
public static void main(String[] args) {
//these are my objects created, name and cost are the first two parameters for each, and then the rest are dependant on the individual constructors, the costs for each object have the original price and no luxury tax added yet because its supposed to be calculate after creating object
Food pastryItem = new Pastry("Croissont", 1.99, 200, "Chocolate");
Boat motorItem = new Motorboat("Evinrude", 3475.00, 400, 5);
Boat yachtItem = new Yacht("Oceano", 950000.00, 1500, 12);
Food fishItem = new Caviar("Beluga", 570.00, 800, "Caspian Sea");
//I know that my inital value prices are right, but I can't calculate the separate luxury taxes for the luxury items (yacht and caviar) and I can't calculate the total sales tax without the total price, which i am unable to get below
pastryItem.getDescription();
motorItem.getDescription();
yachtItem.getDescription().toString();
fishItem.getDescription();
System.out.println("\nTotal price: $" + (pastryItem.getCost() + motorItem.getCost() + yachtItem.getCost() + fishItem.getCost()));
//The output is continously 'Total price: $954046.99' which i know is just the individual digits adding together then carrying over, but that isn't what I want, I want the entire prices to add together than calculate sales tax, print that then print the total price wiht the sales tax for the grand total
}
}
I apoligize for the long writing and thank you in advance for any help! Please bear in mind that I am a beginner and so I won't know a lot of advanced methods or solutions that aren't well known. Thanks.
So basically my program is a StudySchedule where it takes user input (StudyTime, Subjects, PrioritizedSubjects, PriorityScale) and then creates a schedule based off each of those values. It begins with a class CreateSchedule which takes all the user input and then my other class CalculateScheduleTime takes the input and makes calculations (Calculate does extend to Create).
But when I request the variables from CreateSchedule, to CalculateScheduleTime, the variables appear as 0.0 rather than the number I had put in.
class CreateSchedule extends Test {
public String ScheduleName;
public double userStudyTime;
public double userSubjects;
public double userPrioritySubjects;
public double userSubjectScale;
public String getScheduleName() {
ScheduleName = setScheduleName();
return (ScheduleName);
}
public double getuserStudyTime() {
userStudyTime = setuserStudyTime();
return (userStudyTime);
}
public double getuserSubjects() {
userSubjects = setuserSubjects();
return (userSubjects);
}
public double getuserPrioritySubjects() {
userPrioritySubjects = setuserPrioritySubjects();
return (userPrioritySubjects);
}
public double getuserPriorityScale() {
userSubjectScale = setuserPriorityScale();
return (userSubjectScale);
}
public static String setScheduleName(){
System.out.println("What would you like to name your Schedule?");
Scanner sch = new Scanner(System.in);
return sch.nextLine();
}
public static double setuserStudyTime(){
System.out.println("How many hours are you studying for?");
Scanner sch = new Scanner(System.in);
return sch.nextDouble();
}
public static double setuserSubjects (){
System.out.println("How many subjects are you studying?");
Scanner sch = new Scanner(System.in);
return sch.nextDouble();
}
public static double setuserPrioritySubjects (){
System.out.println("How many subjects are you prioritizing?");
Scanner sch = new Scanner(System.in);
return sch.nextDouble();
}
public static double setuserPriorityScale (){
System.out.println("On a scale of 1 - 5, how much priority would you like to give the prioritized subjects?");
Scanner sch = new Scanner(System.in);
return sch.nextDouble();
}
public double confirm() {
System.out.println("Input Results:");
System.out.println("Schedule Name: " + ScheduleName);
System.out.println("Study Time: " + userStudyTime);
System.out.println("Subjects: " + userSubjects);
System.out.println("Priority Subjects: " + userPrioritySubjects);
System.out.println("Priority Scale" + userSubjectScale);
return (0);
}
}
class CalculateScheduleTime extends CreateSchedule {
public double SubjectPriorityTime;
public double SubjectRemainderTime;
public CalculateScheduleTime() {
}
public double calcSubjectPriorityTime() {
System.out.println("Priority" + userSubjectScale);
double PriorityPercent = ((double) (userSubjectScale / 5.0));
System.out.println(userSubjectScale);
SubjectPriorityTime = ((double) (PriorityPercent * userStudyTime));
System.out.println("Time to Prioritized Subject is: " + SubjectPriorityTime);
return (SubjectPriorityTime);
}
public double calcSubjectRemainderTime() {
System.out.println("Remainder");
SubjectRemainderTime = ((double) (SubjectPriorityTime - userStudyTime));
System.out.println("Remainder time to Subject is: " + SubjectRemainderTime);
return (SubjectRemainderTime);
}
}
public class Test {
public static void main(String[] args) {
CreateSchedule user = new CreateSchedule();
user.getScheduleName();
user.getuserStudyTime();
user.getuserSubjects();
user.getuserPrioritySubjects();
user.getuserPriorityScale();
user.confirm();
CalculateScheduleTime calc = new CalculateScheduleTime();
calc.calcSubjectPriorityTime();
calc.calcSubjectRemainderTime();
}
}
That's not what subclassing is for.
A class describes what a given instance can do. "Dog" is a class. "Lassie" is an instance of it.
Subclassing is a thing you do to concepts, not instances. You might for example have a class "Animal", and a subclass "Dog": Dog simply specializes Animal: Any Dog is also an Animal and therefore can do and has all the properties that all Animals have, and perhaps a few additional things and properties (in java parlance: It would have all fields and methods of the superclass, and can add more. It cannot remove any).
When you write CreateSchedule user = new CreateSchedule(); that's like writing: Dog rover = new Dog(); - then you write CalculateScheduleTime calc = new CalculateScheduleTime(); which is like writing GermanSchnauser fifi = new GermanSchauser();.
You made a whole new dog, which gets its own copy of all those fields, which are all still 0 - uninitialized.
The 'calc' stuff should just go in CreateSchedule, probably. But there is a ton wrong with this code:
Classes represent tangible concepts. A good class name is 'Schedule'. Or perhaps 'ScheduleCreator'. 'CreateSchedule' is not a proper class name, and thinking about it as 'the code for creating schedules' is just plain incorrect, the right way to think about classes is about what they represent. "It is the code that explains what Schedules can do and how to create them", that's a proper way to think about it (and that class would be called Schedule. Not CreateSchedule).
methods named getX should not have sideeffects.
You should not be making a new scanner every time.
setters take an argument. They don't ask the user.
Separate concerns. A Schedule should just do schedule stuff - something else should be doing the interaction with the user. Either a main method or a class for this (perhaps TextBasedScheduleCreator).
Those calcX() methods store the result in a field, return it, and that field is never actually used anywhere. Just return it, don't have that field.
I'm trying to grasp some comments that were made to me by my professor on a programming assignment. The assignment was to write a program that calls upon another class. This program was to take 2 investors with different starting balances and show how much interest they would collect after a 15 month period.
Just so everyone is clear, my assignment has already been graded, so any critiques or changes would NOT be helping me complete my homework, but ONLY to help me understand what I did wrong and how I can fix it for future assignments. I received a 90% on my program for my grade.
The following comments were made about my assignment:
"Your setInterest method was to be a class method not an instance
method. Also, your call should have been
IWUnit4Ch13Investor.setInterest(rate);"
I'm not exactly following what I did wrong or how I can fix it. Can someone please show me what I did wrong and possibly explain why it's wrong so that I may correct my habits for future assignments and grasp how to correctly write code?
// IWUnit4Ch13.java
import java.util.*;
import java.util.Scanner;
// main class
public class IWUnit4Ch13 {
public static void main(String[] args) {
// Declares local variables
double rate, INTEREST_RATE;
// Instantiate investor1 & investor2 objects using a two parameter constructor
IWUnit4Ch13Investor investor1 = new IWUnit4Ch13Investor(1001, 2000);
IWUnit4Ch13Investor investor2 = new IWUnit4Ch13Investor(2001, 4000);
Scanner input = new Scanner(System.in);
// Receives the APR by the user
System.out.print("Please enter the APR in the form of .05 for 5%: ");
rate = input.nextDouble();
// Moves the decimal 2 places to the left (used later)
INTEREST_RATE = rate * 100;
// Sets the interest rate using a class variable
investor1.setInterestRate(rate);
investor2.setInterestRate(rate);
// Prints the header for the table
System.out.printf("Monthly balances for one year with %.2f annual interest:\n\n", rate);
System.out.println("Month Account # Balance Account # Balance");
System.out.println("----- --------- ------- --------- -------");
// Loop that prints each month on the table
// Uses class variables to add interest and get balance for display
for (int i = 1; i <= 15; i++) {
investor1.addInterest();
investor2.addInterest();
System.out.printf("%5d %9d %9.2f %9d %9.2f\n", i, investor1.getACCOUNT_NUMBER(), investor1.getBalance(), investor2.getACCOUNT_NUMBER(), investor2.getBalance());
}
// Prints the calculated interest earned by both investors
System.out.printf("\nInvestor1 earned : %.2f", investor1.getInterest());
System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
System.out.print("%\n");
System.out.printf("Investor2 earned : %.2f", investor2.getInterest());
System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
System.out.print("%\n\n");
} // end of internal main
} // end of main class
// Creates IWUnit4Ch13Investor.java which is used in IWUnit4Ch13.java
public class IWUnit4Ch13Investor extends IWUnit4Ch13 {
// All variables are declared private
private static double interestRate; // class variable
private final int ACCOUNT_NUMBER; // declare constant ACCOUNT_NUMBER
private double balance; // instance variable called balance
private double initialBalance; // to hold the initial balance
private double interest; // to count how much interest was made
private double INTEREST_RATE; // used to convert the float interestRate to int
// Two parameter constructor to initialize account number and balance
public IWUnit4Ch13Investor(int acctNum, double initialBalance) {
this.initialBalance = initialBalance;
this.ACCOUNT_NUMBER = acctNum;
balance = initialBalance;
}
// To return the balance to parent
public double getBalance() {
return balance;
}
// Class method to set the annual interest rate
public void setInterestRate(double rate) {
interestRate = rate;
}
// Method to add interest based on balance * interestRate / 12
public void addInterest() {
balance += balance * interestRate/12.0;
}
// To get account number in parent
public int getACCOUNT_NUMBER() {
return ACCOUNT_NUMBER;
}
// Used to get the amount of interested earned during 15 months
public double getInterest() {
interest = balance - initialBalance;
return interest;
}
} // end of class
Thank you all in advance for your help.
Terms
First of, please don't confuse terms. A variable is different to a method:
// A class
public class Dog {
// Member variable
private String name;
// Method
public void bark() {
// Variable
String textToBark = "Wuff";
// Call to a method
System.out.println(textToBark);
}
}
Elsewhere:
// Creating a new instance of class "Dog"
// and saving a reference to it inside a variable
Dog bello = new Dog("Bello");
Explanation
Your teacher said he wants the setInterest to be a class method instead of an instance method. What he wants to say with that is that it should be declared static and thus not belonging to instances of the class but to the class itself. Here is more on what static means for methods: Java: when to use static methods
Solution
So the method should look like this:
// Method to set the annual interest rate
public static void setInterestRate(double rate) {
IWUnit4Ch13Investor.interestRate = rate;
}
Where interestRate then also needs to be declared static (which you already did):
// To count how much interest was made
private static double interestRate;
To indicate the access of static variables one should add the class name before, so instead write it like this:
// Method to add interest based on balance * interestRate / 12
public void addInterest() {
balance += balance * IWUnit4Ch13Investor.interestRate / 12.0;
}
The same holds for calling static methods, instead of
investor1.setInterestRate(rate);
investor2.setInterestRate(rate);
do this
IWUnit4Ch13Investor.setInterestRate(rate);
Due to the nature of static you then also need to set this only once since static variables are shared by all instances of that class.
So a static variable is shared by all instances of the class.
If you want all investors to be forced to share the same interest rate, use a static variable.
Methods that only affect static variables should (https://www.ietf.org/rfc/rfc2119.txt) be declared static:
public static void setInterestRate(double rate) {
interestRate = rate;
}
private static double interestRate;
You would then call the static method by specifying the class name, not the instance variable. Note that you can call the static method before you even have any instances of the class, and you only need to call it once:
Investor.setInterestRate(0.05);
Investor i1 = new Investor();
Investor i2 = new Investor();
double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();
If you want each investor to be able to have different interest rates, do not use a static variable, use a member variable and method:
public void setInterestRate(double rate) {
interestRate = rate;
}
private double interestRate;
You then call the method by specifying the instance variable:
Investor i1 = new Investor();
Investor i2 = new Investor();
i1.setInterestRate(0.04);
i2.setInterestRate(0.06);
double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();
Also, none of that really matters because the output is wrong:
double monthly_rate = pow(10.0, log10(1.0 + yearly_rate) / 12.0) - 1.0;
The system shall not fail
As is, it does compile.
Bug = printing breed and declawed statements on same line. Cannot get rid of this bug for some reason
Bug = unable to get the result logic to compile and print for
console (newb)
There are examples a little like mine posted but they really haven't done anything to help because they are not exactly what I think I'm supposed to be going for. One worked perfect but uses and array and we aren't even to that part yet in my course. Here are the teachers instructions and some tips he gave me and then my code so far. Some of it is commented out since I'm trying to get rid of bugs before printing the result. Also I did change some of the names for convenience until the assignment is complete. Sorry for any formatting issues. Any advice?
In this order:
assignment instruction for class file
tip from the teacher
class file code so far
assignment for the driver file
driver file code so far
ASSIGNMENT INSTRUCTIONS FOR THE CLASS FILE:
Create a new class called Cat that includes the functionality below
The new class has the attributes of:
name – type String
age – type integer
weight – type double
breed - type String
declawed - type boolean - true for has no claws, false for has claws
Be sure your classes have a reasonable complement of constructor, accessor and mutator methods. Every member variable must have at least one independent accessor and one independent mutator.
Example:
public void setName(String name) mutator used to set name
public void setBreed(String breed) mutator used to set the breed
public void set(Boolean declawed) used to set claws or not
****(You must overload the set method to set deClawed value)** what is this?**
public String getName() accessor used to get name
public String getBreed() accessor used to get breed
public boolean getBoolean() access used to get the value of declawed
Ensure you use the “this” reference from within this class when referring to every instance variable or instance method of the current object.
TIP FROM THE TEACHER:
for your IF statement you will only use Age and Claw methods but
then at the end when you print out everything you will need the rest of the
methods. You can create a display method to display all the print
statements for each category such as name, age, etc...then it becomes
easier to display this in the main method - here would be your code in the
main method:
System.out.println("The cat data entered is: \n");
myCat1.display();
myCat2.display();
myCat3.display();
code for class file so far
/*************************************************************************************************
*Cat.java
*Jonathan Nees
*
*Cha. 6 OOP
*************************************************************************************************/
import java.util.Scanner;
public class Cat
{
private String name;
private int age;
private double weight;
private String breed;
private boolean declawed;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return this.age;
}
public void setWeight(double weight)
{
this.weight = weight;
}
public double getWeight()
{
return this.weight;
}
public void setBreed(String breed)
{
this.breed = breed;
}
public String getBreed()
{
return this.breed;
}
public void setDeclawed(boolean declawed)
{
this.declawed = declawed;
}
public boolean isDeclawed()
{
if (!this.declawed == false)
{
return true;
}
else
{
return false;
}
}
Scanner input = new Scanner(System.in);
public void display()
{
System.out.print("Enter the name of Cat: ");
this.name = input.nextLine();
System.out.print("Enter the age of Cat: ");
this.age = input.nextInt();
System.out.print("Enter the weight of Cat: ");
this.weight = input.nextDouble();
System.out.print("Enter the breed of Cat: ");
this.breed = input.nextLine();
System.out.print("Does the cat have claws? True or False?: ");
this.declawed = input.nextBoolean();
}
}
Assignment instructions for the driver file
Write a driver program that reads in 3 pets of type Cat and prints out the name and age of all cats with claws and over 3 years old.
The following information should be read in:
Name (as String)
Age (as int)
Weight (as double)
Breed (as String)
DeClawed (as boolean)
Ensure you use the accessor methods to check the age and claws.
code for driver file so far
/*************************************************************************************************
*CatDriver.java
*Jonathan Nees
*
*Cha. 6 OOP Driver
*************************************************************************************************/
import java.util.Scanner;
public class CatDriver
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Cat Cat1 = new Cat();
Cat Cat2 = new Cat();
Cat Cat3 = new Cat();
Cat1.display();
System.out.println();
Cat2.display();
System.out.println();
Cat3.display();
System.out.println();
//*for (int i=0; i<3; i++)
//{
// System.out.println("The cats over 3 with claws are:");
// if ((!this.age() <= 3) && (this.Declawed() == true))
// {
// System.out.println("Name: " + this.name);
// System.out.println("Age: " + this.age + "Years Old");
// }
//}
}
}
Like I said I've commented some out to work out the bugs before doing the result.
It almost works! Sorta...
I was able to get it to work. I rewrote your display method using setter methods and it did the trick. Also, your declawed setter method is written a little confusingly so you may want to tinker with it.
Try this:
public void display()
{
System.out.print("Enter the name of Cat: ");
this.setName(input.nextLine());
System.out.print("Enter the age of Cat: ");
this.setAge(Integer.valueOf(input.nextLine()));
System.out.print("Enter the weight of Cat: ");
this.setWeight(Double.valueOf(input.nextLine()));
System.out.print("Enter the breed of Cat: ");
this.setBreed(input.nextLine());
System.out.print("Does the cat have claws? True or False?: ");
this.setDeclawed(!Boolean.valueOf(input.nextLine()));
}
I'm trying to get the toString from the class Employee, but all it does is give me an output of [ ]. I got the input for the toString method, but any ideas on how to get it to carry out to the output?
public class A5
{ // begin class
public static void main(String[] args)
{ // begin main
// ********** CREATE OBJECTS **********
ArrayList<Employee> employeeInfo = new ArrayList<Employee>();
// ********** GET INPUT **********
// get the employee's ID
System.out.println("\nEnter your employee ID.");
ID = keyboard.nextInt(); //get the input and set it to the local varaible ID
//System.out.println("Employee ID: " + ID);
// get the employee's hours worked
System.out.println("\nEnter the amount of hours you worked this week.");
Hours = keyboard.nextInt(); //get the input and set it to the local varaible HoursWorked
//System.out.println("Hours worked: " + Hours);
// get the employee's wage
System.out.println("\nEnter your wage.");
Wage = keyboard.nextDouble(); //get the input and set it to the local varaible Wage
//System.out.println("Employee wage: " + Wage);
// ********** OUTPUT **********
System.out.println(employeeInfo.toString());
// ********** CLOSING MESSAGE **********
System.out.println("\nEnd of Processing!");
} // end main
} // end class
And the other class is:
public class Employee
{ // begin class
private int ID; // employee's id
private int Hours; // number of hours worked
private double Wage; // pay per hour
public Employee(int IDnumber)
{
ID = IDnumber;
}
public int getID()
{
return ID;
}
public void setWage(double HourlyWage)
{
Wage = HourlyWage;
}
public double getWage()
{
return Wage;
}
public void setHours(int hoursWorked)
{
Hours = hoursWorked;
}
public double getHours()
{
return Hours;
}
public String toString() // overrides the toString method inherited from object
{ // begin toString
String strout = "\nId \t\t Hours \t\t Rate \t\t Regular Pay \t Overtime Pay \t Gross Pay\n";
strout += ID + "\t " + Hours + "\t\t\t $" + (df1.format(Wage)));
return strout;
} // end toString
} // end class
You are calling the toString method of the ArrayList, not of any Employee. In fact you did not yet create an instance of that class. Try:
System.out.println(new Employee());
EDIT:
First:
OK, well, you need atleast to make some Employee objects and add them to your list ;) Otherwise, there is "nothing" (which prints out to "nothing"). So after you read all your stuff from the user's input (ID and so) make a new Employee out of it:
// make a new employee
Employee employee = new Employee(id); // pass your id
employee.setWage(...); // pass your wage
... // pass other things
// add it to the list of course
employeeInfo.add(employee);
Now there is an employee in the list which you can print. You can test if something is on the list by asking for its size:
System.out.println(employeeInfo.size());
Second:
You don't call toString() on your employee class, which you properly want to print. You call it on your list of employees. Therefor you will see the result of the toString() method of the ArrayList class (which is not what you expect, but what is correct). Instead, iterate over the list and print every employee. Note that the toString() method will be called automatically, since System.out.println will convert your object to a string (which actually means to call this method).
Try this:
for(Employee employee: employeeInfo)
System.out.println(employee);
Your employeeInfo object seems to be empty, and thus you are printing an empty list.
Make sure you put values in it before printing.
Note that the toString() of the ArrayList is implemented to recursively invoke toString() of its object, so it is fine to use ArrayList.toString() to print the entire ArrayList - if that's what you want. No need to iterate for all elements.
You are printing the toString of an Array. employeeInfo is an ArrayList of Employees.
Iterate and print employees like:
for (Employee e : employeeInfo)
{
System.out.println(e.toString());
}