Combining get method with variables inside a secondary get/set method Java - java

I'd appreciate it if anyone could help. Just what seems like a novice question but I can't figure it out.
I have 3 classes Class1, Class2, UseClass.
In Class1 I have a get/set method (COST is used elsewhere in Class1 but not in those methods)
int class1Num;
final double COST = 120;
public int getNum()
{
return class1Num;
}
public void setNum(int newNum)
{
class1Num = newNum;
}
In Class2 I have a final variable and a normal variable and another get/set method.
Class2 extends Class1.
final double FINALNUM = 50;
double totalNum;
public double getTotalNum()
{
return totalNum;
}
public void setTotalNum(int class1Num)
{
totalNum = COST * getNum() + FINALNUM;
}
public void display()
{
System.out.println("Final Number: " + getTotalNum() );
}
Basically what I need to do is I need to in Class2. First multiply COST by the getNum() method from Class1 and then add FINALNUM to that total. This is just my recent attempt but I've tried adding FINALNUM in the system.out to no avail (although multiplication works fine for some reason).
display() is called in the UseClass to output the final result.
I have no other ideas and not exactly sure what I'm looking for when searching online so I figured asking here may help
Any help would be great
Thanks.

According to your statements, the classes are following I guess:
public class Class1 {
int class1Num;
final double COST = 120;
public int getNum()
{
return class1Num;
}
public void setNum(int newNum)
{
class1Num = newNum;
}
}
public class Class2 extends Class1{
final double FINALNUM = 50;
double totalNum;
public double getTotalNum()
{
return totalNum;
}
public void setTotalNum(int class1Num)
{
// Note: need assign field member "class1Num" inherited from Class1.
// Otherwise, it will be zero and cause incorrect value of getNum()
totalNum = COST * getNum() + FINALNUM;
}
public void display()
{
System.out.println("Final Number: " + getTotalNum() );
}
}
The problem is that "setTotalNum(int class1Num)" doesn't assign class1Num which inherited from Class1. You can call "setNum(class1Num);" before" totalNum = COST * getNum() + FINALNUM;"
public class Class2 {
...
public void setTotalNum(int class1Num) {
setNum(class1Num);
totalNum = COST * getNum() + FINALNUM;
}
....
}

Related

When I change arguments in a method other classes which are calling same very method get disturbed

I have three classes for now one is the main class,
Class A:
class A{
int result;
int getHeightBase() {
return result;
}
void setHeightBase(int h, int b) {
result=h*b;
}
}
Class B:
This class will perform different calculations than A
class B{
int result;
int getHeightBase() {
return result;
}
void setHeightBase(int h, int b) {
result=12*h*b;
}
}
MainClass:
public class Main {
public static void main(String[] args) {
A a= new A();
B b= new B();
calculateArea(a,b);
}
void calculateArea(A obj1, B obj2){
obj1.setHeightBase(5,6);
obj2.setHeightBase(5,6);
}
}
Now, when I change arguments of class A method setHeightBase or class B method setHeightBase for some reason I got to change in MainClass as well where I am sending integer values , and I think this opposes design patterns, could anyone please guide me how to get rid of this, I want to change arguments later on but I don't want to effect any other class or change any other class, I tried to use interface but did not get how to get rid of this problem
thanks a lot in advance , any help would be appreciated
Let's say you have this class:
public void printNumbers(int one, int two) {
int result = one + two;
System.out.println("result = " + result);
}
And this is being called from multiple other classes. You can't just change the signature (returntype, method name, parameterlist) and expect everything to work just fine.
Now, let's assume you don't want it to automatically print a sum, but you want to be able to choose what action to take addition or subtraction.
For the current method, don't change anything. It's been used for addition. So, you'll add an overloaded method, which accepts an additional parameter:
public void printNumbers(int one, int two) {
int result = one + two;
System.out.println("result = " + result);
}
public void printNumbers(int one, int two, String action) {
// action is either add or sub
if ( !"add".equals(action) && !"sub".equals(action) ) {
System.out.println("Error");
} else if ("add".equals(action) {
int result = one + two;
System.out.println("result = " + result);
} else {
int result = one - two;
System.out.println("result = " + result);
}
}
Once you did that, you can change the original method to:
public void printNumbers(int one, int two) {
printNumbers(one, two, "add");
}
public void printNumbers(int one, int two, String action) {
// action is either add or sub
if ( !"add".equals(action) && !"sub".equals(action) ) {
System.out.println("Error");
} else if ("add".equals(action) {
int result = one + two;
System.out.println("result = " + result);
} else {
int result = one - two;
System.out.println("result = " + result);
}
}
and the functionality that was once provided will remain the same, while you won't have to change any other existing code
You can use method overloading,
void setHeightBase(int h, int b) {
result=12*h*b;
}
void setHeightBase(double h, double b) {
result=12.0*h*b;
}
this will save the previous method and also creates a method with exact name and different arguments.
I would use an abstract class as the base and extend other classes from it. The public methods in the abstract class will act as the contract to the outside world. In future, if you want to expose other method you add them to the interface and depending on the functionality, you could provide a default implementation. In real world scenarios, you avoid changing an existing contract.
As an example, your classes can be written as such
abstract class Shape{
int height;
int base;
Shape(int height, int base){
super();
this.height = height;
this.base = base;
}
public int area(){
return height * base;
}
}
class Shape1 extends Shape{
Shape1(int height, int base){
super(height, base);
}
}
class Shape2 extends Shape{
Shape2(int height, int base){
super(height, base);
}
#Override
public int area(){
return 12 * height * base;
}
}
public class Test{
public static void main(String args[]){
Shape s1 = new Shape1(2,3);
Shape s2 = new Shape2(2,3);
System.out.println(s1.area());
System.out.println(s2.area());
}
}

count the number of objects created by java

I'm trying to count the number of objects created but it always returns 1.
public class Drivertwo {
public static void main(String[] args) {
Employee newEmp = new Employee();
Employee newEmp2 = new Employee();
Calculate newcal = new Calculate();
Clerk newclerk = new Clerk();
float x;
int y;
newEmp.setEmp_no(2300);
newEmp.setEmp_name("W.Shane");
newEmp.setSalary(30000);
newEmp.counter();
newEmp2.setEmp_no(1300);
newEmp2.setEmp_name("W.Shane");
newEmp2.setSalary(50000);
newEmp2.counter();
newclerk.setEmp_name("Crishane");
newclerk.setEmp_no(1301);
newclerk.setGrade(2);
newclerk.setSalary(45000);
newclerk.counter();
System.out.println("Salary is:" + newcal.cal_salary(newclerk.getSalary(), newclerk.getEmp_no()));
System.out.println("Name is:" + newclerk.getEmp_name());
System.out.println("Employee number is:" + newclerk.getEmp_no());
System.out.println("Employee Grade is:" + newclerk.getGrade());
System.out.println("No of objects:" + newEmp.numb);
This is my class with the main method
public class Employee {
private int salary;
private int emp_no;
private String emp_name;
public int numb=0;
public int getSalary() {
return salary;
}
public int getEmp_no() {
return emp_no;
}
public String getEmp_name() {
return emp_name;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
public void setEmp_no(int newEmp_no) {
emp_no = newEmp_no;
}
public void setEmp_name(String newEmp_name) {
emp_name = newEmp_name;
}
}
public int counter() {
numb++;
return numb;
This is my Employee class
I tried to run counter in my employee class as a starter but it always returns 1. I know I can make a counter in main class and everytime I make a new object I can get the counter but I want to automatically increase the numb by 1 when an object is made.
You need to make numb static so that there will only be one copy for every instance of the class. As it is, every single Employee object has its own copy of numb.
Also instead of creating a method to up the counter why not just put it in the constructor:
public Employee() {
numb++;
}
numb is an instance variable, meaning that each Employee object will have its own numb, that will be initialized by 0.
If you want all the Employee instances to share the same numb, you should make it static.
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor instance block is preferred
//make this program generic. Because if you add the increment in the constructor
//it won't work for parameterized constructors
{
noOfObjects += 1;
}
// various types of constructors
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("Rahul");
System.out.println(Test.noOfObjects);
}
}
Since static members initialized only once and it will be same for each and every instances of class.
class YourClass {
private static int numb;
public YourClass() {
//...
numb++;
}
public static int counter() {
return numb;
}
}
So simple;-
make this modifications
make numb static like, public int numb=0;,
remove numb++; from method count() and
create constructor public Employee{numb++;}

Player class winning percentage java

I am trying to create a method for " winning percentage " in a player class. I know I need to incorporate total wins divided by total games played, but the code is meant to be simple so I cannot use complex code. (beginner project in computer science) Any useful feedback would be great as I have spent multiple days attempting this and getting no where. By the way, ties count as half a win.
Update: Implemented the getters into the getWinningPercentage method. Also calculated everything inside the getWinningPercentage and removed the setWinningPercentage considering it was useless code. Results were as follows:
Bob
5 wins, 1 losses, 2 ties
Winning percentage = 0.75
public class Player
{
private int numWins = 0;
private int numTies = 0;
private int numLosses = 0;
private String name;
public void setWins(int w)
{
numWins = w;
}
public int getWins()
{
return numWins;
}
public void setTies(int t)
{
numTies = t;
}
public int getTies()
{
return numTies;
}
public void setLosses(int L)
{
numLosses = L;
}
public int getLosses()
{
return numLosses;
}
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
public void incrementWins()
}
numWins++;
}
public void incrementTies()
{
numTies++;
}
public void incrementLosses()
{
numLosses++;
}
public double getWinningPercentage()
{
double totalGames = getWins() + getTies() + getLosses();
double totalWins = getWins() + (getTies() / 2.0);
double winningPercentage = (totalWins / totalGames);
return winningPercentage;
}
}
The winning percentage should be a calculated property, not a field, and not have a setter method. Instead there should only be a "getter" (public double getWinningPercentage()) method and you should calculate and return this value from within the method itself from the other fields that your class already has.
We should leave it up to you to create this method and formula yourself.

Using returns from two different methods in subclass

I'm struggling with one of the final parts of a school assignment.
I had asked this question on another question I had but did not receive an answer.
I have two methods in my super class that I need to use in my sub class and the one method must be invoked inside of the other to return a result, I'm stumped on how to do this.
public class Pay
{
private float hours;
private float rate;
private int hrsStr;
float gross;
double tax;
public void calc_Payroll()
{
if (hrsStr != 0)
gross = hrsStr + ((hours - hrsStr) * 1.33f) * rate;
else
gross = hours * rate;
}
public void tax(double a)
{
if (gross <= 399.99)
tax = .92;
else
if (gross <= 899.99)
tax = .88;
else
tax = .84;
}
public void setHours(float a)
{
hours = a;
}
public float getHours()
{
return hours;
}
public void setRate(float a)
{
rate = a;
}
public float getRate()
{
return rate;
}
public void setHrsStr(int a)
{
hrsStr = a;
}
public int getHrsStr()
{
return hrsStr;
}
}
That is the entire superclass and i need to call the calc_Payroll() method and the tax() method to the subclass, well I need tax() to be inside calc_Payroll() because I need to calculate the net pay from those two methods.
public class Payroll extends Pay
{
float net;
#Override
public void calc_Payroll()
{
//I need to calculate the the net pay here.
}
}
Are you struggling with the syntax of Java?
public class Payroll extends Pay
{
float net;
#Override
public void calc_Payroll()
{
// you can call `super.calc_Payroll()`
// you can call `tax(double a)`
}
}

Calling an external class object from function on main class

I am writing a program that keeps track of different transactions
done over time. I have a main class, and also another class named
CheckingAccount.java.
I have a main class formatted this way.
public class Main
{
public static void main (String[] args)
{
CheckingAccount c = new CheckingAccount(bal);
--line of code---
--line of code---
--line of code---
}
public static int getTransCode()
{
--line of code---
}
public static double getTransAmt()
{
--line of code---
}
public static void processCheck(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.15;
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);
}
public static void processDeposit(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.10;
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);
}
}
This is my CheckingAccount.java
public class CheckingAccount
{
private double balance;
private double totalServiceCharge;
public CheckingAccount(double initialBalance)
{
balance = initialBalance;
totalServiceCharge = totalServiceCharge;
}
public double getBalance()
{
return balance;
}
public void setBalance(double tAm, int Code, double charge, boolean mChrg)
{
if(tCode == 1)
balance = (balance - tAm) - charge;
else //if(tCode == 2)
balance = (balance + tAm) - charge;
}
public double getServiceCharge()
{
return totalServiceCharge;
}
public void setServiceCharge(double currentServiceCharge)
{
totalServiceCharge = totalServiceCharge+currentServiceCharge;
}
}
So the lines I can't get to work are CheckingAccount.setBalance() and CheckingAccount.setServiceCharge() inside the functions on my main class. What I'm trying to do is to call the the methods I created (setBalance, and setServiceCharge) in my class, from functions that I created on my main class (processCheck, and processDeposit).
But I cannot get it to run, I keep running with these error messages.
non-static method setBalance(double,int,double,boolean) cannot be referenced from a static context
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
You are calling your setBalance through classname which is wrong.... setBalance() method is non-static, so it is defined to specific instance of the class, not for a class..
**CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);**
You need to create an instance of CheckingAccount to call the method..
Secondly, in your constructor of CheckingAccount class, you haven't passed any argument for totalService, but you are setting one with an unknown variable..
You will get a compiler error there..
Either you need to initialize your totalServiceCharge with a fixed value or, you can pass it as an argument from main.. And change your constructor as below..
public CheckingAccount(double initialBalance, ** double totalServiceCharge)
{
balance = initialBalance;
this.totalServiceCharge = totalServiceCharge;
}
Then from main, call it like this: -
CheckingAccount ca = new CheckingAccount(bal, totalServiceCharge);
One of the possible solution is:
You need to create object for CheckingAccount before calling method.
Example:
public static void processDeposit(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.10;
CheckingAccount ca = new CheckingAccount();
ca.setBalance(trAm,tCode,curCharge,monthCh);
ca.setServiceCharge(curCharge);**
}
Another way is, change setBalance method as static method.
public static void setBalance(double tAm, int Code, double charge, boolean mChrg)
{
if(tCode == 1)
balance = (balance - tAm) - charge;
else //if(tCode == 2)
balance = (balance + tAm) - charge;
}
I think first approach makes more sense than second approach.
CheckingAccount.setBalance and CheckingAccount.setServiceCharge are not static methods (and in this context, they shouldn't be).
You need to pass a reference of the account to your methods...
public static void processCheck(CheckingAccount ca, double trAm, int tCode, boolean monthCh)
{
double curCharge=0.15;
ca.setBalance(trAm,tCode,curCharge,monthCh);
ca.setServiceCharge(curCharge);**
}
public static void processDeposit(CheckingAccount ca, double trAm, int tCode, boolean monthCh)
{
double curCharge=0.10;
ca.setBalance(trAm,tCode,curCharge,monthCh);
ca.setServiceCharge(curCharge);
}
The you would be able to do something like...
public static void main (String[] args)
{
CheckingAccount c = new CheckingAccount(bal);
processCheck(ca, 100.0, 1, false);
}

Categories