My homework tells me to do this....
a. Create a class named Purchase. Each Purchase contains an invoice number,
amount of sale, and amount of sales tax. Include set methods for the invoice
number and sale amount. Within the set() method for the sale amount, calculate
the sales tax as 5% of the sale amount. Also include a display method that displays
a purchase’s details. Save the file as Purchase.java.
b. Create an application that declares a Purchase object and prompts the user
for purchase details. When you prompt for an invoice number, do not let the
user proceed until a number between 1,000 and 8,000 has been entered.
When you prompt for a sale amount, do not proceed until the user has entered
a nonnegative value. After a valid Purchase object has been created, display
the object’s invoice number, sale amount, and sales tax. Save the file as
CreatePurchase.java.
This is what I have so far......
import java.util.*;
public class Purchase{
public double invoiceNumber;
public double saleAmount;
public double salesTax;
public void setInvoice(double number){
this.invoiceNumber = number;
}
public void saleAmount(double sale){
this.salesTax = sale*.05;
this.saleAmount = sale;
}
public void displayPurchase(){
System.out.print("Invoice Number " + invoiceNumber + " Sale Amount " + saleAmount + " Sales Tax " + salesTax);
}
}
import java.util.*;
public class CreatePurchase extends Purchase{
Scanner input = new Scanner(System.in);
double inputSale = input.nextDouble();
double inputNumber = input.nextDouble();
public void valueChecker(){
if(1000 >= inputSale && inputSale <= 8000){
saleAmount(inputSale);
invoiceChecker();
}
else if(inputSale <= 0){
System.out.print(" Not a valid invoice ");
}
}
public void invoiceChecker(){
setInvoice(inputNumber);
displayPurchase();
}
public static void main(String[] args){
}
}
Why isn't this working?
because you haven't called anything in main method. Your main method is empty.
public static void main(String[] args){
// you need to call other methods from here
CreatePurchase purchaseObject = new CreatePurchase();
purchaseObject.valueChecker();// or whatever method you want to call depending upon your logic.
}
import java.util.Scanner;
public class CreatePurchase extends Purchase {
public void invoiceChecker(double inputnumber, CreatePurchase cp) {
cp.setInvoice(inputnumber);
cp.displayPurchase();
}
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
double inputSale = input.nextDouble();
double inputNumber = input.nextDouble();
CreatePurchase cp = new CreatePurchase();
System.out.println(inputSale + " " + inputNumber);
if (inputSale >= 1000.0 && inputSale <= 8000.0) {
cp.saleAmount(inputSale);
cp.invoiceChecker(inputNumber, cp);
} else if (inputSale <= 0.0) {
System.out.print(" Not a valid invoice ");
}
}
}
TestInput and Output;
1500.2
3.0
1500.2 3.0
Invoice Number 3.0 Sale Amount 1500.2 Sales Tax 75.01
1)Do you get any compile time error?
Method invocation of java search for main method to execute but in the current
main method, It does not have anything to execute or NIL calls
public static void main(String[] args){
}
So nothing will be executed.Call the methods from the main method with the required inputs so that main methods will execute with the call invocation.
Related
This assignment is to calculate the cost of a hospital visit. I am trying to ask the user what the prices for the "overnightCharge", "medicationCharge", and "labCharge" are. I then try to use the input to add them together in the method called "total". Next, I try to print the resulting/returned variable from "total" method in the main method by typing System.out.println("Your total charge is: " + total(totalCost). I thought total(totalCost) would retrieve the variable returned by "total" method.
package hospitalstay;
import java.util.Scanner;
/* total charges
if overnight charges
medication charges
lab charges
ask user if new patient*/
public class HospitalStay {
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(totalCost); // i want to print the "totalCost variable" returned by the "total" method.
}
public static double overnightCharge () {// asking user for overnight charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your overnight charge");
double overnightCharge;
overnightCharge = sc.nextDouble();
return overnightCharge;
}
public static double medicationCharge() {// asking user for medication charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your medication charge");
double medicationCharge;
medicationCharge = sc.nextDouble();
return medicationCharge;
}
public static double labCharge() {//asking user for lab charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your lab charge");
double labCharge;
labCharge = sc.nextDouble();
return labCharge;
}
public static double total (double medicineCharge, double labCharge, double overnightCharge) {
double totalCost;
if (overnightCharge == 0) {
totalCost = (overnightCharge + medicineCharge + labCharge); //Calculating all three charges
}
else {
totalCost = (medicineCharge + labCharge);
}
return totalCost;
}
}
You have changeв the total method to
public static double total () {
return overnightCharge() + medicineCharge() + labCharge();
}
Also change main method to
public static void main(String[] args) {
System.out.println("Your total charge is: " + total());
}
First of all, you've defined three parameters for method "total," but you are specifying only one argument in your main method:
total(totalCost)
to minimize the number of things that you need to change in your code, I would simply change the total() method to:
public static double total() {
double totalCost = overnightCharge();
totalCost += medicationCharge();
totalCost += labCharge();
return totalCost;
}
and in your main method:
public static void main(String[] args) {
System.out.println("Your total charge is: " + total();
}
You are passing the wrong inputs to total, change your main to
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(medicationCharge(), labCharge(), overnightCharge()));
}
Also, in your total method, you don't need the if condition, so you can simplify it to:
public static double total(double medicineCharge, double labCharge, double overnightCharge) {
return (overnightCharge + medicineCharge + labCharge);
}
"Explanation why your code didn't work as desired: "
You have created a function total() which takes 3 arguments i.e (double medicineCharge, double labCharge, double overnightCharge)
public static double total (double medicineCharge, double labCharge, double overnightCharge) {
return totalCost;
}
But when you are calling this function in your main() you are only passing it a single argument that is total(totalCost).
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(totalCost); // i want to print the "totalCost variable" returned by the "total" method.
}
You have also made a typo mistake "medicineCharge"
You can try something like this to achieve your desired output :
import java.util.Scanner;
public class Hospital {
static Scanner input;
private static double overnightCharge, medicationCharge, labCharge,
totalCost;
public static double takeInput() { // single function to take input
input = new Scanner(System.in);
return input.nextDouble();
}
public static double overnightCharge() {// asking user for overnight charge
System.out.println("What is your overnight charge");
overnightCharge = takeInput();
return overnightCharge;
}
public static double medicationCharge() {// asking user for medication
// charge
System.out.println("What is your medication charge");
medicationCharge = takeInput();
return medicationCharge;
}
public static double labCharge() {// asking user for lab charge
System.out.println("What is your lab charge");
labCharge = takeInput();
return labCharge;
}
public static double total() {
overnightCharge();
medicationCharge();
labCharge();
if (overnightCharge == 0) {
totalCost = (overnightCharge + medicationCharge + labCharge); // Calculating
// all
// three
// charges only when overnightCharge = 0
} else {
totalCost = (medicationCharge + labCharge);
}
return totalCost;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Total :" + total());
}
}
Note: I have also reduced the code for calling scanner again again.
I tried searching for this answer and found several answers that were similar to what I am looking for, but I can't seem to apply the suggestions provided on unrelated data to my specific program.
I need to take this working code I have created (a program to calculate an employee's annual compensation) and adjust it in a way that shows two classes (per the instructions of my homework assignment). The output given is exactly what I want, I just need help to reorganize the code so there is more than the main class. Is this something I can get help with here?
Here is my working code:
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
double commissionPercentage = 0.06;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
double totalCompensation = (value * commissionPercentage) + salary;
System.out.println("Your annual compensation is: " + "$" + totalCompensation);
}
}
Thanks in advance.
create a class Employee with salary and commissionPercentage as the fields.
In constructor take the salary and commision% of employee and initate the fields.
in this class Employee create a method which will take vavlue as input and will calculate the compensation and return it.
So from main create the instance of Employee class and call the calculateMethod.
I would structure it with these classes:
AnnualCompensationCalculator which will do the computation for you as a utility class, and
AnnualCompensation main class which would be focused on requesting for the user input (and would call the calculator).
Suppose you can move the logic inside new class.
AnnualCompensationCalculator.java
public class AnnualCompensationCalculator{
private static double commissionPercentage = 0.06;
public static double calculateCompensation(double sales ,double salary){
return((sales * commissionPercentage) + salary);
}
}
AnnualCompensation .java
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
System.out.println("Your annual compensation is: " + "$" + AnnualCompensationCalculator.calculateCompensation(value,salary));
}
}
Following Object Oriented Programming, I suggest you create a new class Employee that holds the salary and compensation percentage of an employee, which also has a method for calculating the compensation.
Like this:
class Employee {
private double salary;
private double commPercent;
public Employee(double salary, double commPercent) {
this.salary = salary;
this.commPercent = commPercent;
}
public double calculateCompensation(double totalSales) {
return (totalSales * commPercent) + salary;
}
/* Setters & Getters */
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getCommPercent() {
return commPercent;
}
public void setCommPercent(double commPercent) {
this.commPercent = commPercent;
}
}
Then have your main class use this Employee class to do all the work:
public class AnnualCompensation {
public static void main(String[] args) {
//Initialize an Employee object
Employee emp = new Employee(60000, 0.06);
//Create command output for the user to get directions to enter value
System.out.print("Enter total amount of sales for the year: ");
Scanner input = new Scanner(System.in);
double salesAmt = input.nextDouble();
//Calculate the compensation based on the user input then print it
System.out.println("Your annual compensation is: $"
+ emp.calculateCompensation(salesAmt));
}
}
I am trying to write a java program which have two classes. The second class will have the main method and for checking the balance of the account and. The first class will have three methods one for opening an bank account, one for deposit and one for withdrawal. All input needs to be given by user. I am new to java and stuck after at one point any help would be appreciated.
import java.util.Scanner;
class Balance {
static int account()
{ Scanner minimumAmount = new Scanner(System.in);
int openingAmount = minimumAmount.nextInt();
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account:" + openingAmount);
if (openingAmount > 1000)
{
System.out.println("Your Bank account has opened successfully");
int ac = minimumAmount.nextInt();
System.out.println("Enter your account number" + ac);
}
}
static int withdrawal() {
Scanner withdrawalAmount = new Scanner(System.in);
int w = withdrawalAmount.nextInt();
System.out.println("Withdrawal Amount is :" + w);
int b = openingAmount - w;
if (b < 100) {
System.out.println("Unable to process your request");
}
}
void deposit() {
Scanner depositAmount = new Scanner(System.in);
int d = depositAmount.nextInt();
System.out.println("Deposited amount is :" + d);
int b = openingAmount + d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
}
}
i) Is there a way where an user input variable declared under one method can be used in another method to declare another variable?
ii) ow to return a value from a method so that the value received works in different method while declaring a variable?
Is there a way where an user input variable declared under one method
can be used in another method to declare another variable?
You can declare your attribute in your class and use constructor to initialize it for example :
class A{
private String name;
public A(String name){
this.name = name
}
public int account(){
//can use and change the name
}
public int withdrawal(){
//can use and change the name
}
public int deposit(){
//can use and change the name
}
}
Main class
public class B{
public static void main(String[] args) {
A s = new A("Hello");
//------------^^---pass your attribute in the constructor
s.account();
s.withdrawal();
s.deposit();
}
}
How to return a value from a method so that the value received works
in different method while declaring a variable?
You can use the result of each method in another method for example :
s.withdrawal(s.account());
//--------------^^-------account return a result that can be used by withdrawal
I don't know what you really want to do, but I can explain some things.
Methods account() & withdrawal() don't have to be static.
You can use instance attribute like I do to store values.
Balance & AccountBalance should be in different files.
Take a look about private & public on attribut & methods (& getter/setter)
Scanner is a little bit tricky so you should declare it once, and reuse it.
If you want to use returned value from function, change void by int (in this case) and use "return var" (var is what you want to return). So when you can call the function like this -> int value = s.account();
Try this code, it works.
Cheers !
import java.util.Scanner;
class Balance {
private Scanner scanner;
public int userAccount;
public int userAccountNumber;
public Balance() {
scanner = new Scanner(System.in);
}
public void account() {
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account : ");
int openingAmount = scanner.nextInt();
if (openingAmount > 1000) {
System.out.println("Your Bank account has opened successfully");
userAccount = openingAmount;
System.out.println("Enter your account number : ");
userAccountNumber = scanner.nextInt();
} else {
System.out.println("Not enought money");
this.account(); //Ask again for opening an account
}
}
public void withdrawal() {
System.out.println("Withdrawal Amount is : ");
int w = scanner.nextInt();
int b = userAccount - w;
if (b < 100) {
System.out.println("Unable to process your request");
} else {
userAccount = b;
}
}
public void deposit() {
System.out.println("Deposited amount is : ");
int d = scanner.nextInt();
userAccount += d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
System.out.println("Final amount is : "+s.userAccount);
}
}
The program I am working on currently runs successfully but it doesn't execute part of my program and it shows no errors.
The prompt was:
"Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1000 and 8000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a non-negative number, sale amount, and sales tax. Save the file as CreatePurchase.java."
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
double tax = .05;
double totalamount;
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
while (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
}
while (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
}
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount(double totalAmount) {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
double totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
I have spent hours trying to figure out what I need to fix in order to get my display method to work. The program runs successfully, and there are no errors, so I am not sure what to even try to fix.
(Sorry if my code or question doesn't make sense.)
I would massively refactor your code if given the chance. First, the CreatePurchase class should be a simply POJO (plain old Java object), containing state for the invoice number, purchase amount, and sales tax, along with getter and setter methods for accessing and changing that state. Next, the main() method within this class will instantiate a CreatePurchase object for storing the user input. A big change I made was in how the code handles user inputs. My code below uses two while loops to poll the user for a correct invoice number (between 1000 and 8000) and amount (non negative), and only then proceeds with the remainder of the method. Finally, the CreatePurchase object created is used to output the result to the console.
public final class CreatePurchase {
private int invoiceNum;
private double amount;
private double totalamount;
// I am hard-coding the sales tax as 5%, as you did in your question,
// though this code can easily be modified if you also want to input the tax
private final double tax = .05;
public int getInvoiceNum() {
return invoiceNum;
}
public void setInvoiceNum(int invoiceNum) {
this.invoiceNum = invoiceNum;
}
public double getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
public static void main(String[] args) {
CreatePurchase cp = new CreatePurchase();
Scanner input = new Scanner(System.in);
// these next two do-while loops will continue polling the user
// until he enters a valid input
do {
System.out.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
} while (invoiceNum < 1000 || invoiceNum > 8000);
cp.setInvoiceNum(invoiceNum);
do {
System.out.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
} while (amount < 0);
totalamount = amount*(1 + tax);
cp.setAmount(amount);
cp.setTotalAmount(totalAmount);
// now use the CreatePurchase object to print out
// details of the transaction
System.out.println("Your invoice number is:" + cp.getInvoiceNum() + ".");
System.out.println("Your sale amount is: " + cp.getAmount() + ".");
System.out.println("Your sale amount after tax is: " + cp.getTotalAmount() + ".");
}
}
You declared method public void display(int invoiceNum, double amount, double totalAmount) but you never actually used it.
try the below code, this should help!
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
static double tax = .05;
static double totalAmount;
public void updatePurchase(final Purchase purchase) {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
if (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
updatePurchase(purchase);
}
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
if (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
updatePurchase(purchase);
}
setTotalAmount(tax, amount);
display(invoiceNum, amount, getTotalAmount());
}
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
new CreatePurchase().updatePurchase(completedPurchase);
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
Having an issue receiving the "Just Tax." Program compiles, will not calculate sales tax on output - simply returns a "0." The "Sale" method (not within listed code) will acknowledge and print the amount of the sale, however. Not sure what I'm doing incorrectly. Thanks!
//...
Purchase saleAmount = new Purchase();
//...
System.out.println("Please enter a positive (+) number for the sale amount: $");
double saleAmt = input.nextDouble();
saleAmount.setSale(saleAmt);
//...
System.out.println("The 5% tax applied is: " + saleAmount.getJustTax());
public class Purchase
//all data types have been declared
final double SALES_TAX = 0.05;
{
//Initial Sale Cost
public double getSale()
{
return sale;
}
public void setSale(double amount)
{
amount = sale;
}
//Get Just Sales Tax
public double getJustTax()
{
return justTax;
}
public void setJustTax(double sale)
{
justTax = (sale * SALES_TAX);
}
}
The assignment in your setSale method is backwards. Currently, it assigns whatever is in sale to your local variable amount.
Change
public void setSale(double amount)
{
amount = sale;
}
to
public void setSale(double amount)
{
sale = amount;
}
public void setSale(double amount)
{
amount = sale;
}
This is causing the issue. What you're currently doing is taking the method argument and assigning your sale variable to it. (I cannot see it in the code however).
public void setJustTax(double sale)
{
justTax = (sale * SALES_TAX);
}
This means when the above code is called, sale still has no value to it and I'll guess that sale is instantiated with 0.