Struggles in using multiple classes - java

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.

Related

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.

Method is undefined for the type, very new to java

I'm just starting to learn Java and for one of my assignments I need to run the variable sales from this class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Commission_main_module_improved {
// Local variables
//Declare Real sales, commissionRate, commission, advancedPay
static float sales;
static float commissionRate;
static float commission;
static float advancedPay;
{
sales = 0.12f;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Get the amount of sales.
//sales = getReal("Enter the salesperson's monthly sales")
System.out.print("Enter the salesperson's monthly sales");
sales = Float.parseFloat(br.readLine());
// Get the amount of advanced pay.
//advancedPay = getReal("Enter the amount of advanced pay, or \n 0 if no advanced pay.")
System.out.print("Enter the amount of advanced pay, or \n 0 if no advanced pay.");
advancedPay = Float.parseFloat(br.readLine());
// Determine the commission rate.
//commissionRate h8= determineCommissionRate(sales)
Float commissionRate = DetermineCommssionRate(sales);
//Display the commission rate
//Display "Commission rate: ", 100 * commissionRate, "%"
commission = commissionRate * sales;
}
}
Through this class
/**
*Nethods In the this class calculate commision rate
*/
public class DetermineCommssionRate {
public static float determineCommissionRate(float sales) {
float cr;
if (sales < 10000f) {
cr = 0.10f;
}
else if (sales < 15000f) {
cr = 0.12f;
}
else if (sales < 18000) {
cr = 0.14f;
}
else {
cr = 0.18f;
}
return cr;
}
public static void main(String[] args) {
System.out.println(determineCommissionRate(17000f));
}
}
In order to calculate the commission rate, but when I try and run the code, I get the error,
The method DetermineCommssionRate(float) is undefined for the type Commission_main_module_improved
at the part in the first class at the line,
Float commissionRate = DetermineCommssionRate(sales);
We did this in class but I haven't been able to replicate it at home. I've been trying to look up how to do this for the last 4 hours and I'm just not understanding exactly what I need to do or what I'm doing wrong, and if this is just a syntax error or if I'm trying to do something impossible. Anything to point me in the right direction is appreciated.
You need to call:
Float commissionRate = DetermineCommssionRate.determineCommissionRate(sales);
instead of
Float commissionRate = DetermineCommssionRate(sales);
since you have to call the Class.Method(argument) instead of just the Class. For future reference you should define your class with a different (noticeably) name than your class. Otherwise it should work fine.
In addition, you call
System.out.println(determineCommissionRate(17000f));
which is a misspelling of the actual method
System.out.println(determineCommssionRate(17000f));
You put determineCommissionRate as the method name, but it actually doesn't have an 'i' in commision.
Hope this helps.
To access your static function use the class name to prefix your method, example below
DetermineCommssionRate.determineCommissionRate(1.5f));

Java set method not working

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.

Move a method to another method java

import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}

Categories

Resources