Accessing a double from one method to another one - java

I am a big beginner in java and just need to know how to use this variable from one method to another as it is part of an assignment. please help.
public class parking {
public static void input(String args[]) {
int hoursParked = IO.getInt("(\\(\\ \n(-,-) How many hours were you parked?\no_(\")(\")");
double bill = hoursParked * 0.5 + 2;
}
public static void output(String args[]) {
System.out.println(" Parking");
System.out.println("$2 Fee plus $0.50 every hour!");
System.out.println("\nYour amount owed is $" + bill + "0");
}
}

In your code, bill is a local variable in input. You cannot refer to that variable from outside input.
If input and output are to be separate methods, then the usual thing would be to make them instance methods and to create a parking instance to use the methods. That lets you store bill as an instance variable (aka "instance field"). (Normally classes are initially capped, e.g. Parking, so I'll do that here.)
public class Parking {
private double bill;
public Parking() {
this.bill = 0.0;
}
public void input() {
int hoursParked = IO.getInt("(\\(\\ \n(-,-) How many hours were you parked?\no_(\")(\")");
this.bill = hoursParked * 0.5 + 2; // Or perhaps `+=`
}
public void output() {
System.out.println(" Parking");
System.out.println("$2 Fee plus $0.50 every hour!");
System.out.println("\nYour amount owed is $" + this.bill + "0");
}
}
(Java makes using the this. when referring to instance members optional. I always advocate using it, as above, to make it clear we're not using a local variable. Other opinions vary, saying it's unnecessary and verbose. It's a matter of style.)
Usage
Parking p = new Parking();
p.input(args);
p.output();
Alternately, return the value of bill from input and then pass it into output:
public class Parking {
public static double input() {
int hoursParked = IO.getInt("(\\(\\ \n(-,-) How many hours were you parked?\no_(\")(\")");
return hoursParked * 0.5 + 2;
}
public static void output(double bill) {
System.out.println(" Parking");
System.out.println("$2 Fee plus $0.50 every hour!");
System.out.println("\nYour amount owed is $" + bill + "0");
}
}
Usage:
double bill = parking.input(args);
parking.output(bill);
Side note: Since neither input nor output did anything with args, I've removed it above.

You can declare as class variables, then access it.
public class parking {
private double bill;
public void input(String args[]) {
int hoursParked = IO.getInt("(\\(\\ \n(-,-) How many hours were you parked?\no_(\")(\")");
bill = hoursParked * 0.5 + 2;
}
public void output(String args[]) {
System.out.println(" Parking");
System.out.println("$2 Fee plus $0.50 every hour!");
System.out.println("\nYour amount owed is $" + bill + "0");
}

Related

Java Bank Account Logic

I am trying to create a bank account class with few tools such as Balance, Deposit and withdrawal. I created super class and two sub class. One of the sub class(checking account) needs to charge a 10$ fee after 2 transactions.
I am having small trouble in the following program. It is a minor part of the program and I tried everything but I can not think of the solution. The problem is marked with star box comment in the code. The bank account (super Class) class is attached for your reference.
It is charging the transaction fee even though withdrawal is failed due to unavailability of enough balance. I understand why it is doing that but can someone suggest any solution?
//This is the sub Class "Checking Account"
public class CheckingAccount extends BankAccount
{
//Private Instance Variablea
private double dTransFee;
private int iFreeCheckPerMonth;
private int iNumChecks;
//Constructor
public CheckingAccount(String sName, int iAccountNumber)
{
super(sName, iAccountNumber);
dTransFee = 10;
iFreeCheckPerMonth = 2;
iNumChecks=0;
}
//Overriding method from the Bank Account Class
public boolean bWithdrawl (double dMoney)
{
if (iNumChecks<2)
{
super.bWithdrawl(dMoney);
iNumChecks++;
iFreeCheckPerMonth--;
}
else
{
/****************************
* I DON'T KNOW HOW I CAN MAKE STATEMENT SUCH AS
* IF BWITHDRAL IS FALSE(FAILS) DON'T TAKE OUT 10 FROM BALANCE.
***************************/
super.bWithdrawl(dMoney);
dBalance = dBalance- dTransFee;
iNumChecks++;
iFreeCheckPerMonth--;
}
return false;
}
//Prints how many checks are left
public int FreeChecksLeft ()
{
return iFreeCheckPerMonth;
}
//Prints how many checks have been used
public int CheckUsed ()
{
return iNumChecks;
}
}
//Super Class
/**************************************************************
*Name: BankAccount
*Input:Name and account number. Deposit and withdrawal amount for methods
*Output: None
*Description:
* Date: 10/19/2017 Author: Apurva Gandhi
**************************************************************/
public class BankAccount
{
//Private Instance Variable
protected double dBalance;
protected int iAccountNum;
protected String sOwnerName;
//Constructor
public BankAccount (String sName, int iAccountNumber)
{
iAccountNum = iAccountNumber;
sOwnerName = sName;
}
/**************************************************************
*Name: deposit
*Input:amount of money
*Output: none
*Description: takes the amount of money and add the amount to the balance.
* Date: 10/19/2017 Author: Apurva Gandhi
**************************************************************/
//Method for deposit
public void deposit(double dMoney)
{
dBalance += dMoney;
}
/**************************************************************
*Name: Withdrawal
*Input:amount of money
*Output: none
*Description: takes the amount of money and subtracts the amount from the balance.
* Date: 10/19/2017 Author: Apurva Gandhi
**************************************************************/
//Method for Withdrawal
public boolean bWithdrawl (double dMoney)
{
if (dMoney <= dBalance)
{
dBalance -= dMoney;
}
return false;
}
//Method to get balance
public double getBalance()
{
return dBalance;
}
}
//Here is the tester for Checking Account
public class CheckingTester
{
public static void main(String[] args)
{
//Create Checking account
CheckingAccount ca1 = new CheckingAccount ("Apurva", 1000);
//Make deposit
ca1.deposit(500);
//Verify that it worked
System.out.println("After deposit the balance is: " + ca1.getBalance()+" Expected:500");
//Check #1
//Test a withdrawal
ca1.bWithdrawl(100);
//Verify that it worked
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 400");
//Checks the number of free checks available for use
ca1.FreeChecksLeft();
System.out.println("Number of Free Checks left are: "+ca1.FreeChecksLeft()+ " Expected 1");
//Check how many checks have been used
ca1.CheckUsed();
System.out.println("The number of check used are: "+ ca1.CheckUsed()+(" Expected 1"));
//Check #2
ca1.bWithdrawl(100);
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 300");
//Check 3
ca1.bWithdrawl(100);
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 190");
//Check 4
ca1.bWithdrawl(200);
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 190");
}
}

how can I compare two values in inheritance in java?

I am trying to create a program that checks which account have lowest cost, but I don't know how to implement this in my program.
I want to select the output of each class separately to compare (dayTimeCost)
This is what I think it may be implemted but I don't know how
if (BronceDayTimeCost < SilverDayTimeCost){ System.out.print("\nThe Bronze Account is cheapest.");}
if (SilverDayTimeCost< BronceDayTimeCost ){ System.out.print("\nThe Silver Account is cheapest.");}
Bronze Class
public class Bronze {
// ----------------- Atributes -----------------------
public int dayMinutes; // daytime telphone minutes used
public double dayTimeCost; //Total daytime calls cost
// ------------- CONSTRUCTORS (inputs) ---------------
public Bronze(int theDayMinutes ) {
dayMinutes = theDayMinutes;
}
// ------------------ METHODS ------------------------
// Calculate Total daytime calls cost
public double calcDayTimeCost(double costDay) {
dayTimeCost = dayMinutes * costDay;
System.out.print("\nCost of daytime calls = " + costDay + "/min"+
"\n\nTotal daytime calls cost = " + dayTimeCost +
"\n");
return dayTimeCost;
}
//toString method to override that in Object
public String toString(){
return(
"\n"
);
}
//Returns the type of account
public String type(){
return "Bronze";
}
}
Silver Class
public class Silver extends Bronze {
private static final double costDay = 0.22;
public Silver(int theDayMinutes ) {
super(theDayMinutes );
}
//Returns the type of account
public String type(){
return "Silver";
}
}
Main Class
import java.util.Scanner;
public class AccountUser {
// ------------------- FIELDS ------------------------
// Create instance of Scanner class
public static Scanner input = new Scanner(System.in);
// variables
public static Bronze bron;
public static Silver silv;
public static int dayMinutes;
// ------------------ METHODS ------------------------
public static void main(String [] args) {
// Input dayMinutes (with error message)
do{
System.out.print("Please daytime telphone minutes used --> ");
dayMinutes = input.nextInt();
if ( dayMinutes <= 0){System.out.print("\n" + "Input value outside the range!!!" + "\n");}
}while( dayMinutes <= 0);
// Create new Bronze instance
bron = new Bronze(dayMinutes);
silv = new Silver(dayMinutes);
// Calculate scheme1, scheme2
bron.calcDayTimeCost(0.12);
silv.calcDayTimeCost(0.22);
System.out.println(bron);
System.out.println(silv);
}
}
You can collect the return type of calcDayTimeCost method into a double variable as shown below and then check which cost is lower using an if and else conditions.
double bronCost = bron.calcDayTimeCost(0.12);
double silverCost = silv.calcDayTimeCost(0.22);
if(bronCost == silverCost) {
System.out.print("\nThe Silver and Bronze Accounts are same cost ");
} else if (bronCost < silverCost){
System.out.print("\nThe Bronze Account is cheapest.");
} else {
System.out.print("\nThe Silver Account is cheapest.");
}
Although your code works, it is not inline with Object Oriented Programming i.e., in general, we create classes inline with the real world objects, but Bronze and Silver two different elements i.e., they don't directly relate/inherit each other.
In other words, when you say ClassA extends ClassB, you are saying that ClassA IS-A ClassB
So, the alternative approach to this is as follows:
public abstract class Metal {
//add fields applicable for all metals
public double calcDayTimeCost() {
//add code here
}
}
public class Bronze extends Metal {
//Bronze specific details
}
public class Silver extends Metal {
//Silver specific details
}

Methods In Java - Void

I am currently learning about methods and using methods. It sometimes confuses my mind when deciding what to put inside the parameters. I have some code where I created three methods and all correspond. What I must do for this program is to display some services and prices and ask the user if he/she would like it. If they say yes, the prices add up until the end of the array. The part I am having trouble with is how to take in the price from main in my third method. I know that I should use a void method because I am not returning anything, just printing out the prices to the user.
Heres my piece of code for this program:
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What automobile make do you own?");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
make(name);
double price = carMaintenance(name);
finalPrice(price);
}
// First Method
public static void make(String name) {
System.out.println("Hello! We will be happy to service your " + name
+ " automobile today!");
}
// Second Method
public static double carMaintenance(String name) {
String[] services = { "Oil Change", "Tire Rotation", "Air Filter",
"Check Fluids" };
double[] prices = { 39.99, 49.99, 19.99, 10.99 };
double Total = 0;
for (int i = 0; i < services.length; i++) {
System.out.println("Do you want a " + services[i] + " for your "
+ name + " " + prices[i] + "? (y/n)");
String answer;
answer = keyboard.nextLine();
if (answer.equals("y"))
{
Total = Total + prices[i];
}
// Third method
public static void finalPrice ( ? )
Specifically this the part I am having trouble with:
// Third method
public static void finalPrice (double price )
The problem is finalPrice is an invalid type for the variabl which is pretty confusing about.
You have to change finalPrice() to accept a double parameter:
public static void finalPrice(double price) { ... }
And pass the value returned by carMaintenance() to finalPrice():
double price = carMaintenance(name);
finalPrice(price);
Note I am assuming you just forgot to paste the rest of the carMaintenance() method. In the end, of course, it should have the return Total statement.
Your second method is lacking a return statement. You can return the total to main and then send it to your third method, as such:
public static void main(String[] args) {
System.out.println("What automobile make do you own?");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
make(name);
double finalPrice = carMaintenance(name);
printFinalPrice(finalPrice);
}
//first method code here
public static double carMaintenance(String name) {
//second method code here, plus:
return total;
}
// Third method
public static void printFinalPrice(double finalprice) {
System.out.println("Your final price is " + finalprice);
}
Pass double from carMaintance to finalPrice
double finalPriceDbl = carMaintenance(name);
finalprice(finalPriceDbl);
and accept double as parameter in finalPrice
public static void finalPrice ( double finalPrice );
also you should return value from carMaintenance with return statemenet
return Total;

Trouble Calling and Using Java Methods

I just started learning Java and I'm trying to write a program based on an assignment sheet (gave this sheet at bottom of the post). However, I really don't quite understand how to use methods all that well. I've written my methods in the "Customer.java" class, and I'm trying to use them in my "TestCustomer.java" class. However, since I really don't know how to do this, it has turned out horribly. I've searched for information on this, but I just seem to keep making myself more confused. Is there any chance you guys could show me the correct way to use these methods, or at least point me in the right direction? Thank you a ton for any help you can provide.
Customer class
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Customer {
public static double taxRate = 0.00;
public static double saleRate = 0.00;
String customerName;
double listSaleAmount;
double saleDiscount = 0;
double netSaleAmount;
double taxAmount;
double saleTotal;
boolean taxable;
public Customer (String CustomerName, boolean taxable) {
}
public double calculateTax (double listSaleAmount) {
saleDiscount = listSaleAmount*saleRate;
netSaleAmount = listSaleAmount-saleDiscount;
if (taxable == true) {
taxAmount = netSaleAmount*taxRate;
}
else {
taxAmount = 0.00;
}
saleTotal = listSaleAmount + taxAmount;
return saleTotal;
}
public String printRecord; {
System.out.println("Customer is " + customerName);
System.out.println("Sale amount is $" + listSaleAmount);
System.out.println("Discount amount is $" + saleDiscount);
System.out.println("Net Sale Amount is $" + netSaleAmount);
System.out.println("Tax amount is $" + taxAmount);
System.out.println("Total Sale Amount is $" + saleTotal);
}
public static double changeTaxAmount (double taxRate) {
Scanner input = new Scanner(System.in);
double userTaxAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Tax Rate? (8.25 & 8.50 for testing)"));
taxRate = userTaxAmount;
return taxRate;
}
public static double changeSaleRate (double saleRate) {
Scanner input = new Scanner(System.in);
double userSaleAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Sale Discount Rate? (0.00 & 7.50 for testing)"));
saleRate= userSaleAmount;
return saleRate;
}
public static String printTaxRate; {
System.out.println("Tax Rate is" + taxRate + "%.");
}
public static String printSaleRate; {
System.out.println("The Sale Rate is" + saleRate + ".");
}
}
TestCustomer class
import java.math.BigDecimal;
public class TestCustomer {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customer1 = new Customer("Annie Smith", true);
Customer customer2 = new Customer("Bob Wilson", false);
Double totalOfAllSales = 0.00;
//I have no clue how to actually use the methods I created in the Customer class!
//These are my best guesses, which are obviously wrong
//Any help here would be greatly appreciated!
Customer.changeTaxAmount(taxRate);
Customer.printTaxRate;
Customer.changeSaleRate(saleRate);
Customer.printSaleRate;
customer1.listSaleAmount = 65.00;
customer2.listSaleAmount = 52.00;
totalOfAllSales += customer1.calculateTax;
totalOfAllSales += customer2.calculateTax;
customer1.printRecord;
customer2.printRecord;
Customer.changeTaxAmount(taxRate);
Customer.printTaxRate;
Customer.changeSaleRate(saleRate);
Customer.printSaleRate;
customer1.listSaleAmount = 84.00;
customer2.listSaleAmount = 105.00;
totalOfAllSales += customer1.calculateTax;
totalOfAllSales += customer2.calculateTax;
customer1.printRecord;
customer2.printRecord;
System.out.println("The total of all sales is $" + totalOfAllSales);
}
}
Assignment sheet (Not worrying about printing to a file right now, just want the main mechanics to work)
You seem to be confused about the syntax for calling a method. The syntax is as follows:
object.method(arguments)
If there are no arguments it looks like this:
object.method()
Also, you need to use accessor and mutator methods instead of directly setting instance variables like you do here:
customer1.listSaleAmount = 65.00;
You should implement methods like these:
public void setListSaleAmount(double lsa) {
listSaleAmout = lsa;
}
public double getListSaleAmount() {
return listSaleAmount;
}
and make listSaleAmount private.
Problem #2: The syntax for defining the methods. You are using this code to define a method:
public static String printTaxRate; {
System.out.println("Tax Rate is" + taxRate + "%.");
}
You should be using this code:
public static String printTaxRate() {
System.out.println("Tax Rate is" + taxRate + "%.");
}
The problem is the weirdly placed semicolon inside the method header.

How do i get my program to count the number of times a method is called?

Ok, I am teaching myself java and I am trying to write a recursive method that can count how many times it is called/used. This is my code so far:
public class FinancialCompany
{
public static void main(String[] args)
{
StdOut.println("Enter your monthly investment: ");
double money= StdIn.readDouble();
double total = Sum(money);
Months();
StdOut.printf("you have reached an amount of $%8.2f", total);
StdOut.println();
}
public static double Sum(double money)
{
double total = (money * 0.01) + money;
if(total >= 1000000)
{
return total;
}
else
{
total =(money * 0.01) + money;
return Sum(total);
}
}
public static int counter = 0;
public static void Months()
{
counter++;
StdOut.println("It should take about " + counter + " month(s) to reach your goal of $1,000,000");
}
}
This is the output:
Enter your monthly investment: 1000 (I chose 1000)
It should take about 1 month(s) to reach your goal of $1,000,000
you have reached an amount of $1007754.58
Every time I run this is prints out final amount but I want it to tell me how many months it took to get there but all it prints out is 1 month. Any help will be greatly appreciated!
**
Completed Code(Thanks to everyone's contributions!)
**
public class FinancialCompany
{
public static int counter = 0;
public static void main(String[] args)
{
StdOut.println("Enter your monthly investment: ");
double money= StdIn.readDouble();
double investment = money;
double total = Sum(money, investment);
StdOut.println("It should take about " + counter + " month(s) to reach your goal of $1,000,000");
}
public static double Sum(double money, double investment)
{
counter++;
double total = (money * 0.01) + money;
if(total >= 1000000)
{
return total;
}
else
{
return Sum(total + investment ,investment);
}
}
}
Zach
Couldn't you just make a global variable like counter outside of the methods?
Sort of like this.
public class testThingy {
public static int counter = 0;
/* main method and other methods here */
}
Just add 1 to counter every time the method is called (within the method you want counted) and it should update the global variable.
Two ways:
1) is to have a variable that exists outside of the method. (If the method lives on an object, you can make it a variable of the object, for example.) At the start of the method, ++variable. Then you can see what value it ends at.
2) is to make the return value, or part of the return value, the number of calls of all of your children. As in:
-If you do not call yourself, return 1.
-If you do call yourself, return the sum of all the return values of all your self-calls (+1 if you also want to count calls of the method part-way through the tree)
Well since you only call Months() once per execution of the application, then counter increments only once! If you want to persist counter between executions of your application, you will have to save the value at the end of the application, and load it in again when you run the application again.
Month() only gets called once in your code, so it sees that counter == 0, then increments that giving counter == 1. This is the value being printed.
So, your counter++ is in the wrong place. It should be inside at the top of the Sum() method. As this is the method being recursively called, this is where the counter should increment.
Now when Month() gets called it will have the proper value.
I believe that this should give you what you are looking for.
public static void main(String[] args)
{
StdOut.println("Enter your monthly investment: ");
double money= StdIn.readDouble();
int months = 0;
while(money < 10000){
money += invest(money);
months++;
}
StdOut.println("It should take about " + String.valueOf(months) + " month(s) to reach your goal of $1,000,000");
StdOut.printf("you have reached an amount of $%8.2f", money);
StdOut.println();
}
private static double invest(double investment){
return (investment + (investement * 0.01));
}

Categories