I have created a business program that takes in double values with a loop and calculates net profit. I am required to add the input values from the main class to a custom class called Business. Then I am supposed to calculate the net Profit in the Business class and print the final value to the main class. When I run my current program, the result is "0.0". The Business class is not getting my input values from my main class, but I can't figure out why. Main class below:
public class BusinessProject {
public static double revenue;
public static double expenses;
public static double TotalRevenue;
public static double TotalExpenses;
public static void main(String[] args) {
Business calc = new Business();
getTotalRevenue();
getExpense();
calc.Profit();
}
public static double getTotalRevenue() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter your revenue: \nJust type 0 when you've finished inputting all values");
revenue = scan.nextDouble();
TotalRevenue += revenue;
if(revenue==0) {
break;
}
}
return TotalRevenue;
}
public static double getExpense() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter your expenses: \nJust type 0 when you've finished inputting all values");
expenses = scan.nextDouble();
TotalExpenses += expenses;
if(expenses==0) {
break;
}
}
return TotalExpenses;
}
}
Second Custom Class:
public class Business {
public static double ExpenseInput;
public static double RevenueInput;
public void REVENUE() {
BusinessProject TOTAL = new BusinessProject();
double RevenueInput = BusinessProject.TotalRevenue;
}
public static void EXPENSE() {
BusinessProject TOTAL2 = new BusinessProject();
double ExpenseInput = BusinessProject.TotalExpenses;
}
public void Profit() {
double difference = (RevenueInput - ExpenseInput);
if (difference <=1000) {
System.out.println("Net Profit: " + (difference - (difference * 0.00175)));
}
}
}
You get 0.0 because you haven't called your methods to set RevenueInput and ExpenseInput.
So in your case calling EXPENSE() and REVENUE() before profit() would solve it.
However, I'd advice you to look over your program structure and naming convention. You could either pass the variables as arguments for your function such as: Profit(double expense, double revenue) or you could have it in the constructor of Business like so: public Business(double expense, double revenue)
What you have right now is a circular dependency where you are relying on static variables in the class(BusinessProject) that your object(Business) then uses.
I would personally refactor it like this:
public class Business {
public static void profit(final double revenue, final double expense) {
double difference = (revenue - expense);
if (difference <=1000) {
System.out.println("Net Profit: " + (difference - (difference * 0.00175)));
}
Then from your main project you simply call Business.profit(TotalRevenue, TotalExpense);
public void Profit(BusinessProject bp) {
double difference = (bp.TotalRevenue - bp.TotalExpenses);
if (difference <=1000) {
System.out.println("Net Profit: " + (difference - (difference * 0.00175)));
}
}
and call it as below
calc.Profit(this);
Instead of passing Business object you are creating new Business object in main class. Hence properties will be initialized with default values
You have to call EXPENSE() and Profit() from main class and you have to pass Business class as parameter to those methods
Related
I've been going back and forward on how to deal with this. I have been trying to take input from user in GradesApp.java and store in my variable "gradesPossible" then pass it to another class Grades.java. I don't mind if it is the same name variable or different. I was trying to use setter or getter method, but I am not very familiar with it.
GradesApp.java :
public class GradesApp {
public static void main(String[] args) {
System.out.print("Enter the total points possible for the class: ");
int gradesPossible = Integer.parseInt(s.nextLine());
I want to access "gradesPossible" in Grades.java
Grades.java:
public class Grades {
public double gradesFor3Classes()
{
double grade1 = (gradesPossible*3);
return grade1;
}
Edited typos
what do you want to do with value of the gradesPossible? If you want to calculate the value, maybe it's something like this:
public class GradesApp {
public static void main(String[] args) {
System.out.print("Enter the total points possible for the class: ");
int gradesPossible = Integer.parseInt(s.nextLine());
Grades grades = new Grades();
double gradeResult = grades.calculateGrade(gradesPossible);
System.out.print("Value Grade: " + gradeResult);
}
}
And this is for Grades class
public class Grades {
public double calculateGrade(int gradesPossible) {
double grade1 = (gradesPossible*3);
return grade1;
}
}
Hope this helps!
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 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);
}
}
I'm beginning to learn more about Java and I'm trying to code a Gratuity calculator that takes user Input, and shows how much a tip would be at %10 and %20 of the total. I'm getting a single "Cannot make a static reference to the non-static method" error that I can't resolve.
Gratuity class:
public class Gratuity{
//variables
private double total = 0;
private double grat1 = 0;
private double grat2 = 0;
public Gratuity(float value){
total = value;
}
start getters and setters
public double getTotal() {
return total;
}
//method to do the calculations
public void calcGrat(){
grat1 = total * .10;
grat2 = total * .20;
}
public double getGrat1(){
return grat1;
}
}
And the class with the main method:
import java.util.InputMismatchException;
import java.util.Scanner; //import package to use the scanner input function
//TestGrat main class contains method
public class TestGrat {
Scanner keyboard = new Scanner(System.in);
//method to prompt user for total, double is total
public void askForInput(){
try{
System.out.println("Enter the total amount of your bill");
total = keyboard.nextDouble();
}
catch(InputMismatchException e){
System.err.printf("Error, please try again. Program will now close");
System.exit(0);
}
}
public Scanner getKeyboard() {
return keyboard;
}
public void setKeyboard(Scanner keyboard) {
this.keyboard = keyboard;
}
//main method
public static void main(String[] args){
// asks for input in float form
float value = askForInput();
//Creating the gratCalc object and storing value as a float (total)
Gratuity gratCalc = new Gratuity(value);
// get the total value and set as float
float tot = (float)gratCalc.getTotal();
// converting the float value into string
System.out.println("You have entered: " + Float.toString(tot));
gratCalc.calcGrat(); //sets grat
// Displaying the options to user
System.out.println("Below are the tips for %10 as well as %20 ");
//getting the value and then displaying to user with toString
float getNum = (float) gratCalc.getGrat1();
float getNum1 = (float) gratCalc.getGrat2();
// using the value of getNum as float to put into toString
System.out.println( "For %10: " + Float.toString(getNum));
System.out.println(" For %20: " + Float.toString(getNum1));
}
}
Any help would be appreciated. Thanks!
askForInput() is inside your class TestGrat. However, in main() you are calling it directly, as if it was static. You probably meant:
TestGrat test = new TestGrat();
float value = test.askForInput();
askForInput() is also returning void, so you probably want to fix that too.
The problem is the following:
(Savings Account Class) Create class SavingsAccount. Use a static
variable annualInterestRate to store the annual interest rate for all
account holders. Each object of the class contains a private instance
variable savingsBalance indicating the amount the saver currently has
on deposit. Provide method calculateMonthlyInterest to calculate the
monthly interest by multiplying the savingsBalance by
annualInterestRate divided by 12—this interest should be added to
savings- Balance. Provide a static method modifyInterestRate that sets
the annualInterestRate to a new value. Write a program to test class
SavingsAccount. Instantiate two savingsAccount objects, saver1 and
saver2, with balances of $2000.00 and $3000.00, respectively. Set
annualInterestRate to 4%, then calculate the monthly interest for each
of 12 months and print the new balances for both savers. Next, set the
annualInterestRate to 5%, calculate the next month’s interest and
print the new balances for both savers.
I solved it all, but the balance is not incrementing -- it is staying the same. It should increment with every change in annual interest rate (at least, that's what I understood).
class SavingsAccount
{
static double annualInterestRate;
private double savingsBalance;
public SavingsAccount(double balance)
{
savingsBalance = balance;
}
public double calculateMonthlyInterest()
{
return (savingsBalance*annualInterestRate)/12;
}
public static void modifyInterestRate(double rate)
{
annualInterestRate = rate;
}
public static double getannualInterestRate(){return annualInterestRate;}
public double getsavingsBalance(){return savingsBalance;}
}
public class SavingsTest
{
public static void main(String args[])
{
SavingsAccount saver1 = new SavingsAccount(2000.0);
SavingsAccount saver2 = new SavingsAccount(3000.0);
SavingsAccount.modifyInterestRate(4);
System.out.printf("Balance for Saver1 = %.2f\nBalance for Saver2 = %.2f\nInterest Rate = %.2f\n\n",saver1.getsavingsBalance()+saver1.calculateMonthlyInterest(),saver2.getsavingsBalance(),SavingsAccount.getannualInterestRate());
SavingsAccount.modifyInterestRate(5);
System.out.printf("New Balance for Saver1 = %.2f\nNew Balance for Saver2 = %.2f\nInterest Rate = %.2f\n\n",saver1.getsavingsBalance(),saver2.getsavingsBalance(),SavingsAccount.getannualInterestRate());
}
}
You are not modifying the value of savingsBalance in this code.
public double addMonthlyInterest() {
savingsBalance += (savingsBalance*annualInterestRate)/12;
return savingBalance;
}
This will return the new balance and 'increment'
In your first print statement, for the first argument you are calculating the balance after calculating the monthly interest and adding them together and didn't set the new value as the value of the class member savingsBalance.
In your second print statement, since you did not set the calculated value back to the class member through a setter, it is simply printing out the original value that the classes were instantiated with.
On a side note, don't do inline calculations in print statements. They are confusing and not easy to read for anyone. A good way is to initialize local members in the method and using them for calculations and printing the local members.
Just wanted to share my answer.
public class SavingsAccount {
private static float annualInterestRate = 0f;
private float savingsBalance;
public SavingsAccount(float balance) {
savingsBalance = balance;
}
public static void setAnnualInterestRate(float t) {
if (t >= 0 && t <= 1)
annualInterestRate = t;
else
throw new IllegalArgumentException("Annual interest rate should be between 0 and 1");
}
private float calculateMonthlyInterest() {
return savingsBalance * annualInterestRate / 12;
}
public float getSavingsBalance() {
return savingsBalance + calculateMonthlyInterest();
}
public float getAnnualInterestRate(){
return annualInterestRate;
}
public String toString() {
return String.format("Balance: %.2f", getSavingsBalance());
}
}
in main
SavingsAccount s1 = new SavingsAccount(2000);
SavingsAccount s2 = new SavingsAccount(3000);
SavingsAccount.setAnnualInterestRate(0.04f);
System.out.println("S1: " + s1);
System.out.println("S2: " + s2);
SavingsAccount.setAnnualInterestRate(0.05f);
System.out.println("S1: " + s1);
System.out.println("S2: " + s2);