Java set method not working - java

Hello I'm new to programming and a first time poster here. I'm having trouble getting a Java application to display the correct values assigned via Set methods in a public class. Specifically the CreatePurchase application returns 0 for all 3 user defined variables (invoiceNumber, saleAmount, salesTax) which are Set in the Purchase public class.
Set and display the values here
public class Purchase
{
private int invoiceNumber;
private double saleAmount;
private double salesTax;
public int getInvoiceNumber()
{
return invoiceNumber;
}
public void setInvoiceNumber(int inv)
{
inv = invoiceNumber;
}
public double getSaleAmount()
{
return saleAmount;
}
public void setSaleAmount(double sale)
{
sale = saleAmount;
}
public double getSalesTax()
{
return salesTax;
}
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
tax = salesTax;
}
public static void displayPurchase(Purchase aPurch)
{
System.out.println("Purchase invoice number is " + aPurch.getInvoiceNumber() + "and the sale amount is " + aPurch.getSaleAmount() + "the taxable amount is " +aPurch.getSalesTax());
}
}
This is the CreatePurchase class that prompts the user for the variables and calls the method to display the values for the new object
import java.util.Scanner;
public class CreatePurchase
{
public static void main(String args[])
{
Purchase aPurchase;
aPurchase = getPurchaseInfo();
Purchase.displayPurchase(aPurchase);
}
public static Purchase getPurchaseInfo()
{
Purchase tempPur = new Purchase();
int invoice;
double value;
double value2;
Scanner input = new Scanner(System.in);
System.out.println("Enter the invoice number:");
invoice = input.nextInt();
while(invoice < 1000 || invoice > 8000)
{
System.out.println("You made an invalid selection");
System.out.println("You entered " + invoice);
System.out.println("Please enter a whole number between 1000 and 8000");
invoice = input.nextInt();
}
tempPur.setInvoiceNumber(invoice);
System.out.println("Enter the amount of the sale:");
value = input.nextDouble();
value2 = (value * .05);
while(value < 0)
{
System.out.println("You made an invalid selection");
System.out.println("You entered " + value);
System.out.println("Please enter a non negative number");
value = input.nextDouble();
value2 = (value *.05);
}
tempPur.setSaleAmount(value);
tempPur.setSalesTax(value2);
return tempPur;
}
}
Any direction or advice on how to get the values entered to set and display properly would be greatly appreciated.

The setter needs to assign the new value to the instance field.
public void setSaleAmount(double sale)
{
sale = saleAmount;
}
Yours do the opposite now, switch the assignment around:
public void setSaleAmount(final double sale)
{
this.saleAmount = sale;
}
You can also optionally add final to the parameter (since you don't intend to change it), and make it clear what the instance field is by using this.. Purely optional, but good practice, and in this case either addition would have resulted in a compile-time error to alert you of the mistake.

Your assignments are wrong(for the setters).
It should be salesTax that is set:
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
tax = salesTax; /* wrong assignment(for the purpose) */
}
And so on for your other class variables.
Remember: Setters and Getters are used to modify a class' variables.

All setters need to be modified as below:
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
//tax = salesTax; <-- This line is wrong..
this.salesTax= tax ; // Change this line and it should work...
}
public void setInvoiceNumber(int inv)
{
//inv = invoiceNumber ; --> Invalid setting
this.invoiceNumber = inv; // Correct setting
}
public void setSaleAmount(double sale)
{
//sale = saleAmount; --> Invalid setting
this.saleAmount = sale; // Correct setting
}
Reason:
tax is local variable which is specific to the method setSalesTax.
salesTax is global variable for the object.
While setting value in your object, you need to set it/assign in the global variable salesTax
To avoid confusions, The best way to use a setter would be:
Object Class:
private double amount;
public void setAmount (double amount)
{
this.amount = amount;
}

It is because you do not set the new Value to your object value.
The correct way would be
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
salexTax = tax; //THIS is the mistake
}
Everytime you want to assign a value to an Object, Integer, or whatever, it goes from left to right. So, if you write:
int value=5;
int value2=10;
value2=value;
Value2 is 5 then.

Your setter method is wrong. You must use actual variable on LHS instead of formal argument.
for Ex, setInvoceNumber method should be like below :
public void setInvoiceNumber(int inv)
{
invoiceNumber = inv ;
}
Here inv is formal argument while invoiceNumber is actual variable which is going to store your value in object. You were assigning value of invoiceNumber to inv variable which has no effect in your code. Same goes for all your setter method.

Related

Struggles in using multiple classes

So currently, I'm struggling to make one particular program in eclipse for an assignment, while I am able to make most of the program, I seem to struggle with the no argument part of the program as well as bringing the pieces of the first class into the second for a brief moment. Here is my code for the first class
// Preparation of the input
import java.util.Scanner;
public class primarySetUp {
public static void main(String[] args) {
// Variable Declaration
double userBagNumber;
double userBagWeight;
// Create Scanner
Scanner input = new Scanner(System.in);
java.util.Date date = new java.util.Date();
// Opening Statement
System.out.println("Welcome to the Coffee Sales Simulation!");
// Get User Input
System.out.println("How heavy do you want the bags to be?");
userBagWeight = input.nextDouble();
System.out.println("How many bags do you want?");
userBagNumber = input.nextDouble();
// Get output
// Date
System.out.println("Todays date: ");
System.out.printf("%tB %<te, %<tY", date);
System.out.println(""); // spacer
// Original Inputs
System.out.printf("\nNumber of Bags: %3.0f", userBagNumber);
System.out.printf("\nWeight of Each Bag: %3.2f", userBagWeight);
System.out.print(" lbs");
// Calling of the Class
secondarySetUp mysecondarySetUp = new secondarySetUp(userBagWeight, userBagNumber);
// End Program
System.out.println("\nThank you for shopping with us!");
}
}
and here is my code for the second class, which is full of errors in this case.
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
public secondarySetUp(double userBagWeight, double userBagNumber) {
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// No argument pricing
public Sale() {
singleBagger = 1;
pounderBagger = 1;
}
// First constructor receiving No argument pricing
public Sale(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
If you have any sort of fixes I could apply, please let me know; I am planning on adding the print statements for the rest of the arguments as well, but I'd like to get Sale() fixed up first.
I see a problem in getSale() where you are trying to use userBagWeight, but that variable doesn't exist outside the constructor parameters, which could create a lot of problems since other methods are calling on it. The constructor taking
double userBagWeight, double userBagNumber, yet it's not assigning them to any fields or doing anything with them.
I missed the part where you are treating Sale() as a constructor, but those are no constructors. The constructor is named after your class name.
public secondarySetUp(double userBagWeight, double userBagNumber)
change Sale() to secondarySetUp and you will be fine.
here how your class should be like :
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
double userBagWeight, userBagNumber;
public secondarySetUp(double userBagWeight, double userBagNumber) {
this.userBagWeight = userBagWeight;
this.userBagNumber = userBagNumber;
singleBagger = 1;
pounderBagger = 1;
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// First constructor receiving No argument pricing
public secondarySetUp(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
this is a keyword to tell the program that we want to use the field "instance variable", if we have a method with parameter that have same name as a field name, then to tell them apart we tell the program this.fieldName to know which one we talking about.

How do i get the value of a method to use in main

i'm still pretty new with Java and am trying to write a program that will show me how much my money is actually getting me whenever i make an ingame purchase.
I'm struggling with getting the value from the method convertYourself() into my main method so that i can combine them.
I think i would most likely need make it a double instead of a void and return it but what would i pass as the parameter?
Thank you!
public class TestCode {
Scanner in = new Scanner(System.in);
public static double gemValue = 0.01;
public static double goldValue = 0.000004;
public static void main(String[] args) {
TestCode test = new TestCode();
test.convertYourself(gemValue);
test.convertYourself(goldValue);
// double sum = how do i get the value of the convertYourself method so i can use it here?
System.out.println("The total value of this bundle is :" + sum);
}
public void convertYourself(double x) {
System.out.println("How many are you buying?");
double currency = in.nextDouble();
double convert = currency * x;
System.out.println("The true value of this is: " + convert);
}
}
You would need to have the method to return a value. That can be done like this:
public double convertYourself(double x) {
System.out.println("How many are you buying?");
double currency = in.nextDouble();
double convert = currency * x;
return convert;
}
//To call it:
double valueReturned = convertYourself(gemValue);
So, you would have to change the method return value from void to double, and use the return keyword to return the value you want.
You can use a return type instead of void for a method.
The return value must then be returned via return {value}.
// return type
// \/
public double convertYourself (double x) {
double convert = /* convert */;
return convert;
}
After that you can store the output in a variable:
double result = convertYourself (/* x */);
To be more specific with the coding part:
public class TestCode {
Scanner in = new Scanner(System.in);
public static double gemValue = 0.01;
public static double goldValue = 0.000004;
public static void main(String[] args) {
// TestCode test = new TestCode(); ... you do not need this as the both methods are inside the same class. Make the convertYourself method as *static*.
double gemValueConverted = convertYourself(gemValue); // call it without the object
double goldValueConverted = convertYourself(goldValue);
double sum = gemValueConverted + goldValueConverted;
System.out.println("The total value of this bundle is :" + sum);
}
public static double convertYourself(double x) { // made the method static and added return type as double
System.out.println("How many are you buying?");
double currency = in.nextDouble();
double convert = currency * x;
System.out.println("The true value of this is: " + convert);
return convert;
}
}

JAVA Get & Set methods with calculations

new to Java and trying to set up get and set methods. Although one I need to do as calculation based off getSalary() multiplied by getMonths() to get a Year to Date total.
I haven't been able to find out if calculations are possible in get or set methods or I may just be such a newbie I have it in the wrong place.
public class Employee_v2
{
//Instance variables
private String first_name;
private String last_name;
private double salary;
private int months;
final double increase= 0.25;
private double year_to_date;
public Employee_v2()
{
//fill in the code to set default values to the instance variables
first_name="";
last_name="";
salary= 0.0;
months= 0;
}
//Constructor initializing instance variables with arguments
public Employee_v2(String f, String l, Double sal, int mo)
{
first_name = f;
last_name = l;
salary = sal;
months = mo;
}
//set arguments
public void setFirst(String f)
{
first_name = f;
}
public void setLast (String l)
{
last_name = l;
}
public void setSalary (double sal)
{
salary = sal;
}
public void setMonths (int mo)
{
months = mo;
}
public void setYtdSalary ()
{
double yearToDateSal;
yearToDateSal = getSalary() * getMonths();
}
//get arguments
public String getFirst()
{
return first_name;
}
public String getLast()
{
return last_name;
}
public double getSalary()
{
return salary;
}
public int getMonths()
{
return months;
}
public double getYtdSalary()
{
return yearToDateSal;
}
//DISPLAY
public void displayEmployee()
{
//display the name and salary of both Employee objects
System.out.println("Employee first name: " + getFirst());
System.out.println("Employee last name: " + getLast());
System.out.printf("Employee salary: $%.2f\n", getSalary());
//complete the code
System.out.println("-------------------------------");
//Determine the year to date salary for both employee
System.out.printf(getFirst() + "'s salary: $%.2f\n", getSalary());
// System.out.println(jas.getSalary());
System.out.printf("Year to date salary: $%.2f\n", getYtdSalary());
//set and display salary with increase
setSalary(getSalary()+ getSalary()*increase);
System.out.printf("New Salary: $%.2f\n", getSalary());
System.out.println();
System.out.println();
}//end method
}//end Class
Calculation are possible in getter and setter. I would do something like this:
public double getYtdSalary(){
double ytd = 0;
ytd = months * salary;
return ytd;
}
Like this you can calculate the year to date on the fly and is always accurate data. For example if you called the setMonths method you would also have to call the setYtdSalary before calling the getYtdSalary.
Also there is no need to call your getters in your class to access your private variables.
I would also suggest using Javadoc comment in your classes as they make it easier to understand what the methods do.
to answer your question: yes it is possible to do calculations
this is also needed in many places, as the main reason to use get and set methods is so you can check or manipulate the values before setting them in your class
I guess your Code will Crash on the printing of the year to date Salary, because the variable yearToDateSal is only valid in the Scope of your set Method.
public void setYtdSalary ()
{
double yearToDateSal;
yearToDateSal = getSalary() * getMonths();
}
you should declare your YearToDateSal variable in the beginning of the class, i.e. rigth after
final double increase= 0.25;
private double year_to_date;
private double yearToDateSal;
and in your setYtdSalary() remove the declaration of yearToDateSal;
this way you should be fine :)

Java method returns the given variable instead of the result

I am new in Java, I am trying to make a program for a wallet the first method should return the wallet current money which it does,but the second one which is supposed to add money to the wallet and return the result of the addition keeps returning me the value I am giving to add(addmoney).
package wallet;
import java.util.Scanner;
public class Wallet {
double money;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Wallet w = new Wallet();
Double money = input.nextDouble();
System.out.println(walletbalance(money));
Double addmoney = input.nextDouble();
System.out.println(w.moneyaddition(addmoney));
}
public static double walletbalance(double bal) {
return bal;
}
public double moneyaddition(double added) {
return money = added + money;
}
}
The observed behavior is result of a side-effect. That is, you expected moneyaddition to return the result of money+added and wonder why the function returned just the added value instead of the sum. There's nothing wrong with the function your looking at, but in the prior call to walletbalance you've never set the money member, so 0 + added makes added. You need to fix the setter for this property, then it works:
public static double walletbalance(double bal) {
money = bal;
return bal;
}

Call Superclass method from overridden Subclass method

I'm sure this has a simple solution, but I'm new to Java and can't work it out.
I have a subclass Payroll that extends a superclass Pay, it contains an overridden method called 'calc_payroll'. From this method, I want to call the superclass method of the same name, and assign the output to a variable in the overriding method. My code is below
public class Payroll extends Pay
{
public double calc_Payroll()
{
double grossPay = super.calc_Payroll();
double taxAmt = tax(grossPay);
double netPay = grossPay - taxAmt;
System.out.println(grossPay);
return netPay;
}
}
Below is the code from the calc_payroll method in the superclass
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
the superclass method functions without issue to calculate and return the gross pay when called from a different subclass, but when calling it from a method with the same name, the print line in the code above (that I have labelled for testing) displays zero's for all variables
Code for full 'Pay' class is below as requested
public class Pay
{
private double ttlHours;
private int stHours;
private double rate;
double grossPay = 0.0;
final double TAXL = 0.07;
final double TAXM = 0.1;
final double TAXH = 0.16;
public void SetHours(double a)
{
ttlHours = a;
}
public void SetHoursStr(int a)
{
stHours = a;
}
public void SetRate(double a)
{
rate = a;
}
public double GetHours()
{
return ttlHours;
}
public int GetStHours()
{
return stHours;
}
public double GetRate()
{
return rate;
}
public double taxRate()
{
double taxRate = 0.0;
if(grossPay <= 399.99)
{
taxRate = TAXL;
}
else if(grossPay <= 899.99)
{
taxRate = TAXM;
}
else
{
taxRate = TAXH;
}
return taxRate;
}
public double tax(double grossPay)
{
double ttlTax = 0.0;
if(grossPay < 400.00)
{
ttlTax += (grossPay * TAXL);
}
else if(grossPay < 900.00)
{
ttlTax += (grossPay * TAXM);
}
else
{
ttlTax += (grossPay * TAXH);
}
return ttlTax;
}
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
}
The subclass Payroll contains no other code
Below is the code that accepts user input to assign values to the initialized variables
public class CalPayroll extends Pay
{
Payroll nPay = new Payroll();
Accept Read = new Accept();
public void AcceptPay()
{
char select = '0';
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
}
public void displayInfo()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println("Gross pay is :" + currency.format(calc_Payroll()));
System.out.println("Tax is :" + percent.format(taxRate()));
System.out.println("Net pay is :" + currency.format(nPay.calc_Payroll()));
Screen.ScrollScreen(1);
}
}
I'm confused!
Its clear from you code that ttlHours, stHours and rate are not initialised with some reasonable value. So when you just call super.calc_Payroll(), values like 0 or 0.0 are used as i explained in my comment. Its good to first set values of these variables before calling super.calc_Payroll().
SetHours(23.4); //some value
SetHoursStr(5); //some value
SetRate(2.3); //some value
Also you don't have constructor for Pay class, try making it and initialising all uninitialised variable in constructor or use setter/getter methods to set and get values.
Since your both classes extends Pay class, it creates the problem which you are facing. When you call SetHours(Read.AcceptInputDouble()), it set the variable inherited by CalPayroll from Pay, not the variables inherited by Payroll class. What you have to do is to set variables for Payroll instance as well as for current class as both extends Pay. Do the following replace your while loop as,
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
nPay.SetHours(GetHours());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
nPay.SetHoursStr(GetStHours());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
nPay.SetRate(GetRate());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
Please post the complete code.
It seems that for some reason your variables of super class method not getting assigned values properly. And they are initialized with their default values which is making everything 0. I'll be able to help better if you paste the complete class.

Categories

Resources