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());
}
}
Related
I'm studying Enums in Java and I have a question that isn't working well on my code.
I did my Enum with seconds and some names, and, later, I did a method that looks for it inside the Enum class.
The idea is to start a counter (that's why I'm using the integer values on Enum) given the name of the operation.
The code is:
public enum Calculator {
plus(30), minus(21), divide(21), times(30);
public int seconds;
public int getSeconds() {
return seconds;
}
Calculator(int seconds) {
this.seconds = seconds;
}
private String name;
Calculator(String name) {
this.name = name();
}
public static Calculator contains(String name) {
for (Calculator ss : Calculator.values()) {
if (ss.name.equalsIgnoreCase(name)) {
System.out.println(name + " input " + ss.name + " enum");
return ss;
}
}
throw new NullPointerException("Invalid name");
}
}
And I have another class that invokes this method.
The following invoker is:
public static void calcInput(String name) {
try {
Calculator.contains(name);
} catch(NullPointerException e){
System.out.println("Invalid parameter, " + e );
}
The thing is that, any input I use, a right or wrong one, it is answering me a NullPointerException. Where am I commiting the mistake?
Thanks in advance!
I'm going to walk through your code and make some comments. Then I will show you some changes you could make.
public enum Calculator {
// convention is to name enum values as constants: UPPER_CASE_WITH_UNDERSCORES
plus(30), minus(21), divide(21), times(30);
// you should not make instance fields public, but private
// because they should not be accessed directly by any other class (in general)
public int seconds;
// methods, like this 'getter' belong below all constructors
public int getSeconds() {
return seconds;
}
Calculator(int seconds) {
this.seconds = seconds;
}
private String name;
// this constructor is never used by your enum values (plus, minus, divide, times)
// if it were used, the name parameter in the line below this one is never used for anything
Calculator(String name) {
// you are trying to set your name field to the name() of the enum value.
// even though this would work, this is not very useful
// since calling MY_ENUM_VALUE.name() already gives you its name
this.name = name();
}
// a method like 'contains' usually returns a boolean value to indicate if this instance does or does not
// contain the parameter you provided. Having a 'contains' method which returns a Calculdator instance is
// confusing to say the least. A better name (judging from the method implementation) would be 'forName'
// then you could do:
// Calculator bla = Calculator.forName("Minus");
// System.out.println(bla == Calulcator.minus);
// which would print "true"
public static Calculator contains(String name) {
for (Calculator ss : Calculator.values()) {
if (ss.name.equalsIgnoreCase(name)) {
System.out.println(name + " input " + ss.name + " enum");
return ss;
}
}
// Opinions are mixed on whether you should throw NullPointerExceptions from your application code
// I personally choose to throw IllegalArgumentException in cases like this
throw new NullPointerException("Invalid name");
}
}
Here is a new version of the code which might do what you expect. I don't understand what the 'seconds' values have to do with the calculator operations though.
public enum Calculator {
PLUS(30),
MINUS(21),
DIVIDE(21),
TIMES(30);
private int seconds;
Calculator(int seconds) {
this.seconds = seconds;
}
public int getSeconds() {
return seconds;
}
public static Calculator forName(String name) {
return valueOf(name.toUpperCase());
}
}
The app class:
public class App {
public static void main(String[] args) {
Calculator calculator = Calculator.forName("Minus");
System.out.println(calculator + " seconds = " + calculator.getSeconds());
}
}
The output is:
MINUS seconds = 21
I've created a simplified version of my current assignment for my programming course.
I've created a test program that asks the user for an input, studentName, studentName is then validated through another class. My end goal is to print out a method called toString() that holds the value the user has entered for the studentName. Right now my program returns null, not the value of studentName. The problem is I'm not sure how to properly set the values with a constructor.
If you could set up a proper constructor and a way to properly print the value the user has entered through the command prompt, I would appreciate it!
Here is the class that contains the main method. Note: I may have declared too many class objects because I was in a hurry.
import java.util.Scanner;
public class TestMcTest
{
TestMcTest2 test3 = new TestMcTest2();
public static void main(String[] args)
{
TestMcTest test2 = new TestMcTest();
TestMcTest2 test = new TestMcTest2();
test2.getStudentInfo();
System.out.println(test.toString());
}
public void getStudentInfo()
{
int valid = 0;
Scanner input = new Scanner(System.in);
do
{
System.out.println("Enter a name for a student");
valid = test3.getStudentName(input.nextLine());
}while(valid == 0);
}
}
Here is the class that holds the validation and the toString() method that I want to call into the main method of the class with the main method.
public class TestMcTest2
{
private String studentName;
public String setStudentName()
{
return studentName;
}
public int getStudentName(String studentName)
{
int valid = 0;
if (studentName.length() != 0)
{
valid = 1;
this.studentName = studentName;
}
return valid;
}
public String toString()
{
return this.studentName;
}
}
You dint set the value of variable studentName so the default value of string is printed i.e. null
In TestMcTest you have do
TestMcTest2 test = new TestMcTest2();
test.setStudentName("singhakash");
System.out.println(test.toString());
and in TestMcTest2 change
public void setStudentName(String studentName){
this.studentName = studentName;
}
this will give the expected output.
Btw your method name says opposite of its functionality.
If you could set up a proper constructor and a way to properly print
the value the user has entered through the command prompt, I would
appreciate it!
public class TestMcTest2{
....
public TestMcTest2(String s){
this.studentName = s;
}
}
You have to use the newly constructor now like this:
TestMcTest2 test3 = new TestMcTest2("hot name");
And you can print it out like this after your do-while
System.out.println(test3.toString());
And I'm pretty sure you need the #Override annotation at the toString() method.
EDIT:
#Override <- add this
public String toString()
{
return this.studentName);
}
Im trying to add a dog (nyHund) which is created in a different class, to an Arraylist i created using a constructor in another class, but whenever i try to use the Arraylist in the "register" class, im getting the error that the arraylist name can't be resolved.
First class:
public class Hund {
private String namn;
private int ålder;
private double vikt;
private String ras;
public Hund(String hundnamn, int hundålder, String hundras, double hundvikt) {
this.namn = hundnamn;
this.ålder = hundålder;
this.ras = hundras;
this.vikt = hundvikt;
}
public String getNamn() {
return namn;
}
public int getÅlder() {
return ålder;
}
public double getSvanslängd() {
if (ras=="tax"){
return 3.7;
}else{
return ((vikt*ålder)/10);
}
}
public String toString() {
return namn + "\n" + ålder + "\n"+ras+"\n"+vikt+"\n"+getSvanslängd();
}
}
Second Class
import java.util.ArrayList;
public class testning {
public static void main(String[] args) {
Hund nyHund = new Hund("Daisy", 13, "labrador", 22.3);
System.out.println(nyHund.toString());
Register.läggTillHund(nyHund);
}
}
And the Third class:
import java.util.ArrayList;
public class Register {
public static void läggTillHund(Hund nyHund){
hundRegister.add(nyHund);
System.out.println(nyHund);
}
private Register(){
ArrayList<Hund> hundRegister = new ArrayList<Hund>();
}
}
The problem i am experiencing is with "hundRegister.add(nyHund)"
any thoughts? or pointers where im going wrong? (very new at Java)
Best Regards
Oskar
The ArrayList you've created is local to your Register constructor. Declare it inside the class, but outside the constructor, as an instance variable, so it's in scope throughout the class.
public class Register {
private ArrayList<Hund> hundRegister;
private Register(){
hundRegister = new ArrayList<Hund>();
}
}
Additionally, it's unclear why the constructor is private. Nothing else can access that constructor. I would make it public.
Also, in getSvanslängd, replace ras=="tax" with "tax".equals(ras). See How do I compare strings in Java?.
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.
I'm stuck with a problem here. I want to change the setter from a attribute from the superclass (parent class) in my subclass (child) however when I overide this method in my subclass I can't access my private attributes from the supperclass. And the point is, they have to stay private.
Superclass (problem: setMinimumVoorraad(int voorraad);)
package domein;
public abstract class Artikel implements Weegbaar
{
private String omschrijving;
private double prijs;
private int aantalInStock;
private int minimumVoorraad;
public Artikel(String omschrijving, double prijs, int aantalInStock, int minimumVoorraad)
{
this.setOmschrijving(omschrijving);
this.setPrijs(prijs);
this.setAantalInStock(aantalInStock);
this.setMinimumVoorraad(minimumVoorraad);
}
#Override
public String toString()
{
String output = String.format(" \n omschrijving: %s \n prijs: %f \n In stock %d (minimumvoorraad = %d) \n", this.omschrijving, this.prijs, this.aantalInStock, this.minimumVoorraad);
return output;
}
//----Getters----
public String getOmschrijving() {
return omschrijving;
}
public double getPrijs() {
return prijs;
}
public int getAantalInStock() {
return aantalInStock;
}
public int getMinimumVoorraad() {
return minimumVoorraad;
}
//----Setters----
public void setOmschrijving(String omschrijving) {
this.omschrijving = omschrijving;
}
public void setPrijs(double prijs) {
this.prijs = prijs;
}
public void setAantalInStock(int aantalInStock) {
this.aantalInStock = aantalInStock;
}
public void setMinimumVoorraad(int minimumVoorraad)
{
if(minimumVoorraad < 2)
this.minimumVoorraad = 3;
else
this.minimumVoorraad = minimumVoorraad;
}
}
Subclass
package domein;
public class Food extends Artikel
{
private String houdbaarheidsDatum;
private double nettoGewicht;
public Food(String omschrijving, double prijs, int aantalInStock, int minimumVoorraad, String houdbaarheidsDatum, double nettoGewicht)
{
super(omschrijving, prijs, aantalInStock, minimumVoorraad);
this.setHoudbaarheidsDatum(houdbaarheidsDatum);
this.setNettoGewicht(nettoGewicht);
}
#Override
public boolean isWeegbaar()
{
return true;
}
//----Getters----
public String getHoudbaarheidsDatum() {
return houdbaarheidsDatum;
}
public double getNettoGewicht() {
return nettoGewicht;
}
//----Setters----
public void setHoudbaarheidsDatum(String houdbaarheidsDatum) {
this.houdbaarheidsDatum = houdbaarheidsDatum;
}
public void setNettoGewicht(double nettoGewicht) {
this.nettoGewicht = nettoGewicht;
}
#Override
public void setMinimumVoorraad(int minimumVoorraad)
{
if(minimumVoorraad < 5)
this.minimumVoorraad = 6;
else
this.minimumVoorraad = minimumVoorraad;
}
}
Someone who can help me?
Thanks in advance.
One possibility is to implement the subclass's setter in terms of the superclass's setter (which, presumably, you do have access to).
For example, assuming the setter is setFoo, then the subclass's version might be:
public void setFoo(Foo f) {
// Do subclass stuff pre-setting, if any
super.setFoo(f);
// Do subclass stuff post-setting, if any
}
The answer given above by NPE is absolutely the best way to go about solving this problem. It is elegant and honors basic inheritance contracts between superclass and subclass. Even in your original post, the subclass is actually more restrictive than the superclass, so doing something like:
#Override
public void setMinimumVoorraad(int minimumVoorraad)
{
if(minimumVoorraad <= 5)
super.setMinimumVoorraad(6);
else
super.setMinimumVoorraad(minimumVoorraad);
}
exactly as NPE suggested would probably work. (Note how I modified your if test. Not sure if it's a typo, but in the original implementation 5 would be a valid minimum, but input like 4 would set it to 6.)
Other (possibly acceptable) patterns would be to:
Make the members in your Parent class protected, which would give visibility. (Realize that you did mention a private restriction; this pattern is solely mentioned to provide a more complete overall answer.)
Delegate the validation logic to another method (that is non-private). This way the child can override the validation method.
And now on to the (probably unacceptable) pattern of using Java reflection:
#Override
public void setMinimumVoorraad(int minimumVoorraad) {
try {
Field field = this.getClass().getSuperclass().getDeclaredField("minimumVoorraad");
field.setAccessible(true);
if(minimumVoorraad <= 5)
field.set(this, 6);
else
field.set(this, minimumVoorraad);
field.setAccessible(false);
}
catch(NoSuchFieldException | IllegalAccessException e) {
// do something
}
}
It's worth noting that if you never ever do this in your entire life you will probably be the better for it. Not only does it completely break all contracts, but it relies on hard-coded Strings to do field name lookups, which in and of itself is pretty painful. But it does exist. And no good answer (already given above by NPE) would be complete without an example of how not to do something...