I'm having an issue with the inherited variables not displaying in the subclass.
Heres the code...
// Class to instantiate and call
public class UseOrder
{
public static void main(String[] args)
{
// Instantiate classes
Order objOrder=new Order();
ShippedOrder objShip=new ShippedOrder();
//Promt for data
objOrder.SetName();
objOrder.SetNum();
objOrder.SetPrice();
objOrder.SetQuantity();
// Display
objShip.Display();
}
}
//Heres the parent class
public class Order
{
//Declare variables
public String CustName;
public int CustNum,QuantityOrdered;
public double Price,TotalPrice;
//Assign Variables using set methods
public void SetName()
{
this.CustName=JOptionPane.showInputDialog("Enter customer Name");
}
public void SetNum()
{
this.CustNum=Integer.parseInt(JOptionPane.showInputDialog("Enter customer number"));
}
public void SetQuantity()
{
this.QuantityOrdered=Integer.parseInt(JOptionPane.showInputDialog("Enter quanntity ordered"));
}
public void SetPrice()
{
this.Price=Double.parseDouble(JOptionPane.showInputDialog("Enter product price"));
}
//Get methods for these variables
public String GetName()
{
return CustName;
}
public int GetNum()
{
return CustNum;
}
public int GetQuantity()
{
return QuantityOrdered;
}
public double GetPrice()
{
return Price;
}
//Method to calculate Total Price
public double ComputePrice()
{
return TotalPrice=QuantityOrdered*Price;
}
// Method to display
public void Display()
{
JOptionPane.showMessageDialog(null,CustName+" with customer number "+CustNum+" ordered "+QuantityOrdered+" products. \nThe price for one unit is " + Price+" and the total price is "+ComputePrice());
}
}
and heres the subclass
public class ShippedOrder extends Order
{
//Shipping and handling value
private double ShipFee=4.00;
// method to override ComputePrice in Order
public double ComputePrice()
{
return super.TotalPrice=(super.QuantityOrdered*super.Price)+ShipFee;
}
//Display the data
public void Display()
{
JOptionPane.showMessageDialog(null,super.GetName()+" with customer number "+super.GetNum()+" ordered "+super.GetQuantity()+" products. \nThe price for one unit is " + super.GetPrice()+" and the total price is "+ComputePrice());
}
}
You populate a different object than you're displaying, so no wonder you get no values. You should change main to
public static void main(String[] args)
{
// Instantiate classes
ShippedOrder objShip=new ShippedOrder();
//Promt for data
objShip.SetName();
objShip.SetNum();
objShip.SetPrice();
objShip.SetQuantity();
// Display
objShip.Display();
}
because every ShippedOrder is also an Order.
public static void main(String[] args)
{
// Instantiate classes
Order objOrder=new Order();
ShippedOrder objShip=new ShippedOrder();
//Promt for data
objOrder.SetName();
objOrder.SetNum();
objOrder.SetPrice();
objOrder.SetQuantity();
// Display
objShip.Display();
}
You never set anything in objShip (the derived class). All your pre-display() method invocations were on objOrder, a different object.
Maybe you meant:
public static void main(String[] args)
{
// Instantiate classes
Order objOrder=new ShippedOrder();
//Promt for data
objOrder.SetName();
objOrder.SetNum();
objOrder.SetPrice();
objOrder.SetQuantity();
// Display
objOrder.Display();
}
objShip and objOrder are separate from one another. When you change order, it will not change ship as they are different objects. You need to call the methods on objShip in this case if you want to display it from that.
ShippedOrder objShip = new ShippedOrder();
objShip.SetName();
objShip.SetNum();
objShip.SetPrice();
objShip.SetQuantity();
objShip.Display();
and remove objOrder completely.
Related
I'm doing a menu-based system where it will calculate my monthly rent using specific variables (double - monthlyRent, double waterBill, double energyBill etc.)
The program starts with prompting the user to select an option:
(1) create a budget invoice (this is where a projected monthly rent invoice will be calculated)
When the user selects this option I want to use an ArrayList to store the monthly rent invoices. I have a variable where the user can put an InvoiceID to search an already existing monthly rent invoices or delete etc.
My problem is how to use specific indexes in my ArrayList to input monthly rent, water bill and so forth and the next index will be a different monthly rent, waterbill, energy bill etc.). In a general sense, store multiple variable and variable types within 1 index of the ArrayList.
My ArrayList is in its own class, different from the function that I want to create to generate monthly budget invoices. My problem is how to prompt user input for each rent variable and store all of those inputs in its proper index of the ArrayList where that specific monthly invoice will be stored. The variables are double, string and int types.
import java.util.ArrayList;
public class InvoicerHub {
static ArrayList<Object> invoicerSys = new ArrayList<Object>();
}
import java.util.ArrayList;
import java.util.Scanner;
public class BudgetInvoice extends InvoicerHub {
protected double monthlyRent ;
protected double waterBill;
protected double energyBill;
protected double carRent;
protected double internetRent;
protected String invoiceID;
public int counter = 0;
static Scanner myScan= new Scanner(System.in);
public double getMonthlyRent() {
return monthlyRent;
}
public void setMonthlyRent(double monthlyRent) {
this.monthlyRent = monthlyRent;
}
public double getWaterBill() {
return waterBill;
}
public void setWaterBill(double waterBill) {
this.waterBill = waterBill;
}
public double getEnergyBill() {
return energyBill;
}
public void setEnergyBill(double energyBill) {
this.energyBill = energyBill;
}
public double getCarRent() {
return carRent;
}
public void setCarRent(double carRent) {
this.carRent = carRent;
}
public double getInternetRent() {
return internetRent;
}
public void setInternetRent(double internetRent) {
this.internetRent = internetRent;
}
public String getInvoiceID() {
return invoiceID;
}
public void setInvoiceID(String invoiceID) {
this.invoiceID = invoiceID;
}
public static InvoicerHub getInvoice()
{
invoicerSys = new ArrayList<>();
if (invoicerSys.isEmpty()== true)
{
} // This is where I'm stuck.
I want to create the below class
associatename:String
workstatus:String
associate() :constructor
getassociatename():String
setassociatename(String):void
getworkstatus()String
tracksassociatestatus():int
setworkstatus(String):void
The trackAssociateStatus method takes the number of days as argument and sets the work status of the associate based on the number of days. The first 20 days they learn “C”, the next 20 days they learn “Java” In the Main class invoke the trackAssociateStatus method and find the work status and display the output.
output:The associate abc work status:Project phase
I tried this....But i got error
//associate class
public class associate{
private int associatename;
private String workstatus;
private int days;
void associate()
{
getassociatename();
setassociatename();
getworkstatus();
tracksassociatestatus();
setworkstatus();
}
public int getassociatename()
{
return associatename;
}
public void setassociatename(int associatename)
{
this.associatename=associatename;
}
public String getworkstatus()
{
return workstatus;
}
public void tracksassociatestatus(int days)
{
if(days<20)
setworkstatus("C");
else
setworkstatus("Java");
}
public void setworkstatus(String workstatus)
{
this.workstatus=workstatus;
}
}
//main class
associate a =new associate();
Scanner in=new Scanner(System.in);
int associateid=0;
String workstatus=null;
int days=0;
System.out.println("Enter the associateid:");
associateid=in.nextInt();
a.associateid=(associateid);
System.out.println("Enter the no of days:");
days=in.nextInt();
a.trackassociatestatus();
System.out.println("The id is "+a.getassocaiteid()+" work status "+a.getworkstatus());
Based on your (seemingly) UML spec, your class would look like the following:
public class Associate {
private String associateName;
private String workStatus;
public Associate() {
// This constructor is optional, a no-args constructor is added by the compiler to any class not explicitly naming a constructor.
}
public String getAssociateName() {
return associateName;
}
public void setAssociateName(String associateName) {
this.associateName = associateName;
}
public String getWorkStatus() {
return workStatus;
}
public void setWorkStatus(String workStatus) {
this.workStatus = workStatus;
}
public int tracksAssociateStatus() {
// TODO write logic here
return 1; // TODO change to whatever you need to return
}
}
You were specifying int for getAssociateName, when associateName is a String. This won't work; you need your getter return type to be the same as your field data type, or you need to convert the data to the method's return type. (The former is best practice).
Constructors don't specify a type, the class name is used and the compiler will understand what you want to do (which is return a new instance of the class). Therefore, your void associate() will tell the compiler "create a method called associate that doesn't return anything".
Well, would be nice if you provide the error itself for us.
But meanwhile, have you notice that your tracksassociatestatus method recieves an integer parameter days, and your constructor passes nothing to it?
So try changing your constructor to be something like:
Public associate() {
getassociatename();
setassociatename();
getworkstatus();
tracksassociatestatus(10);
setworkstatus();
}
For a cleaner code, check the other answer.
If you still have errors, please share them.
import java.util.*;
public class Associate
{
private String associateName;
private int workStatus;
private int days;
Scanner sc = new Scanner(System.in);
public String getAssociateName()
{
System.out.println("Enter the Associate id:");
associateName = sc.nextLine();
return associateName;
}
public void setassociatename(int associatename)
{
this.associateName=associateName;
}
public String tracksAssociatename()
{
return associateName;
}
public int getWorkStatus()
{
System.out.println("Enter the number of days");
days = sc.nextInt();
return days;
}
public void setWorkStatus(String workStatus)
{
this.workStatus=workStatus;
}
enter code here
public `enter code here`int tracksAssociateStatus()
{
return days;
}
public static void main(String args[])
{
Associate obj = new Associate();
obj.getAssociateName();
obj.getworkstatus();
System.out.println("The Associate name "+obj.tracksAssociatename()+" work Status "+obj.tracksAssociateStatus());
}
}
The pet store program should start with the user being able to choose to adopt a pet or give a pet the to the shop. If the user wants to adopt a pet, they should be able to see either all available pets, unless they say they know what type of pet they want, then show only available pets of that type.
The 4 methods that will need to be created for this program should:
add new pets
get a pet adopted
show pets by type
show pets available for adoption
Object Class: Pets.java
import java.util.*;
public class Pets {
public static void main(String[] args){
private double age; // age of the animal (e.g. for 6 months the age would be .5)
private String petName; // name of the animal
private String aType; // the type of the pet (e.g. "bird", "dog", "cat", "fish", etc)
private int collarID; // id number for the pets
private boolean isAdopted = false; // truth of if the pet has been adopted or not
private String newOwner;
private Date adoptionDate;
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
public String getaType() {
return aType;
}
public void setaType(String aType) {
this.aType = aType;
}
public int getCollarId() {
return collarID;
}
public void setCollarId(int collarId) {
this.collarID = collarId;
}
public boolean isAdoptated() {
return isAdopted;
}
public void setAdoptated(boolean isAdoptated) {
this.isAdopted = isAdoptated;
}
public Date getAdoptionDate() {
return adoptionDate;
}
public void setAdoptionDate(Date adoptionDate) {
this.adoptionDate = adoptionDate;
}
#Override
public String toString() {
return "Pets [age=" + age + ", petName=" + petName + ", aType=" + aType + ", collarId=" + collarID
+ ", isAdoptated=" + isAdopted + ", adoptionDate=" + adoptionDate + "]";
}
}
}
You should define the data fields and methods inside the class, but not inside the main()-method. The main()-method is the entry point of your java application and could be used to create an instance of your Pets class.
e.g.:
public static void main(String[] args) {
Pets pet = new Pets();
}
This code is not compiling for 2 main reasons:
You are specifying access modifiers on variables inside a method (in this case main), which is forbidden;
You are writing methods (e.g. getAge) inside another method (main) and trying to return a variable (e.g. age) that is out of that scope, in fact the variable age is not known inside the getAge method, because it's declared in the main method.
You should move the variable declaration to class level, and then have all methods separated using those variables. I'll give you a sketch, not the complete solution:
import java.util.*;
public class Pets {
/* Insert all variable declarations here */
private double age;
/* Constructor if you need it */
public Pets(/* parameters you think you need */) {
// Set attributes when you declare a new Pets()
}
/* Insert all methods you need here */
public double getAge() {
return this.age;
}
The positioning of the main method - for what I've understoon from your description - should be placed outside this class, in another class where the whole application will start to run. The Pet class should serve only for anything concerning pets (the four methods you will need to implement and all getters/setters for retrieving private class variables).
You’ve happened to put about everything — private fields and public methods — inside you main method. That doesn’t make sense. Everything that is in your main, move it outside, right under the line public class Pets {. That should fix your compiler error.
String
name of the car. The name is formed by concatenating the word “Car” to the instance number of this object. For example, the first instance is Car1, the second instance is Car2, and so forth.
So I created a String named car and now I need to make it apply a incrementing number when a new instance is created.
public class CarDash {
public String Car ="Car";
public static int instanceNumber;
}
And then it needs to count how many instances were created
One class variable that is shared for all of the class instances.
instanceNumber
integer
keeps track the number of instances created.
Should i add a counter whenever a certain method is called? Or have it count when the a new Car is named/created?
instanceNumber++;
I dont know if I am making any sense...
You just need to create a constructor and increment the instanceNumber (using ++instanceNumber pre-increment ) then set the car value using instanceNumber variable.
So your constructor will be similar to below.
public CarDash(){
Car="Car"+ (++instanceNumber);
}
Whole class will be as below
public class CarDash {
public String Car = "Car";
public static int instanceNumber;
public CarDash(){
this.Car="Car"+ (++instanceNumber);
}
public static void main(String[] args) {
CarDash car=new CarDash();
CarDash car1=new CarDash();
CarDash car2=new CarDash();
System.out.println(car.Car+" "+car1.Car+" "+car2.Car);
}
}
Out put will be as below.
Car1 Car2 Car3
Try like below.
public class CarDash {
public String Car ="Car";
public static int instanceNumber;
CarDash() {
instanceNumber++;
Car = Car + instanceNumber;
}
public static int getInstanceCount() {
return instanceNumber;
}
}
You can do instanceNumber++; in your constructor.
But take special care in case you are instanceNumber as stati,as this would be shared by all instances.
So,in your case(suppose you have 10 instances),you will get name as Car10 for all instances.
e.g.
public class CarDash {
public String Car ="Car";
public static int instanceNumber;
public CarDash() {
instanceNumber++;
}
public String print(){
return Car+instanceNumber;
}
public static void main(String[] args) {
CarDash carDash=new CarDash();
CarDash carDash1=new CarDash();
CarDash carDash2=new CarDash();
System.out.println(carDash.print());
System.out.println(carDash1.print());
System.out.println(carDash2.print());
}
}
Output ::
Car3
Car3
Car3
Better way :
public class CarDash2 {
public String Car ="Car";
public static int instanceNumber;
public int carId;
public CarDash2() {
instanceNumber++;
carId=instanceNumber;
}
public String print(){
return Car+carId;
}
public static void main(String[] args) {
CarDash2 carDash=new CarDash2();
CarDash2 carDash1=new CarDash2();
CarDash2 carDash2=new CarDash2();
System.out.println(carDash.print());
System.out.println(carDash1.print());
System.out.println(carDash2.print());
}
}
Output::
Car1
Car2
Car3
One.java
public class One {
String asd;
public class() {
asd="2d6"
}
public static void main(String args[]) {
Two a = new Two();
}
}
Two.java
public class Two {
ArrayList<String>data;
String asd;
public Two(String asd){
this.asd=asd;
data.add(this.asd);
}
}
How do I use this asd value of second for third class calling from first class's main method.
**Third class**
Per comments of #Maroun Maroun and #Bennyz, you can create a getter and setter method in your Two class:
import java.util.ArrayList;
public class Two {
ArrayList<String> data;
String asd;
public Two(String asd) {
this.asd = asd;
data = new ArrayList<>(); //<-- You needed to initialize the arraylist.
data.add(this.asd);
}
// Get value of 'asd',
public String getAsd() {
return asd;
}
// Set value of 'asd' to the argument given.
public void setAsd(String asd) {
this.asd = asd;
}
}
A great site to learn about this while coding (so not only reading), is CodeAcademy.
To use it in a third class, you can do this:
public class Third {
public static void main(String[] args) {
Two two = new Two("test");
String asd = two.getAsd(); //This hold now "test".
System.out.println("Value of asd: " + asd);
two.setAsd("something else"); //Set asd to "something else".
System.out.println(two.getAsd()); //Hey, it changed!
}
}
There are also some things not right about your code:
public class One {
String asd;
/**
* The name 'class' cannot be used for a method name, it is a reserved
* keyword.
* Also, this method is missing a return value.
* Last, you forgot a ";" after asd="2d6". */
public class() {
asd="2d6"
}
/** This is better. Best would be to create a setter method for this, or
* initialize 'asd' in your constructor. */
public void initializeAsd(){
asd = "2d6";
}
public static void main(String args[]) {
/**
* You haven't made a constructor without arguments.
* Either you make this in you Two class or use arguments in your call.
*/
Two a = new Two();
}
}
Per comment of #cricket_007, a better solution for the public class() method would be:
public class One {
String asd;
public One(){
asd = "2d6";
}
}
This way, when an One object is made (One one = new One), it has a asd field with "2d6" already.