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
}
Related
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 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");
}
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
newbie here at Java. I'm working on a project to where I collect info from a user for two types of Creatures. The menu would look like:
1. Land based
2. Water based
3. Display Animal
4. Quit.
I'm wanting to collect the user information from the user and then display it back to them. I think I'm stuck on building the object constructors from the different object.
Here's what I have so far:
SuperClass:
package com.animal;
public class Creature {
private String size;
private String weight;
public Creature (String size, String weight){
this.size = size;
this.weight = weight;
}
public String getSize() {return size;}
public void setSize(String size) {this.size = size;}
public String getWeight() {return weight; }
public void setWeight(String weight) {this.weight = weight; }
void displayCr(){
System.out.println("***Creatures***");
System.out.println("Size: " + size);
System.out.println("Weight: " + weight);
This is my Land Subclass:
package com.animal;
public class Land extends Creature {
private String landAnimal;
public String getLandAnimal() {return landAnimal;}
public void setLandAnimal(String landAnimal) {this.landAnimal = landAnimal;}
public Land(String size, String weight, String landAnimal) {
super(size, weight);
this.landAnimal = landAnimal;
This is my Water subclass:
package com.animal;
public class Water extends Creature {
private String fish;
public String getFish() {return fish;}
public void setFish(String fish) {this.fish = fish;}
public Water(String size, String weight, String fish) {
super(size, weight);
this.fish = fish;
}
Then this is my Main called Kingdom:
package com.animal;
import java.util.ArrayList;
import java.util.Scanner;
public class Kingdom {
public static void main(String[] args) {
ArrayList<Creature> user = new ArrayList<Creature>();
Scanner input = new Scanner(System.in);
int selection = 0;
while(selection != 4){
System.out.println("****Main Menu****");
System.out.println("Enter 1 for Land Animal");
System.out.println("Enter 2 for Water Animal");
System.out.println("Enter 3 to Display Animal");
System.out.println("Enter 4 to quit");
selection = input.nextInt();
if(selection==1 || selection==2){
Creature userInfo = null;
System.out.println("Enter Size ");
String size = input.next();
System.out.println("Enter Weight: ");
String weight = input.next();
}
if(selection == 1){
System.out.println("Enter Land animal type: ");
String landAnimal = input.next();
//userInfo = new Land(size, weight, landAnimal);
//user.add(userInfo);
}
else if(selection == 2){
System.out.println("Enter Water animal type: ");
String fish = input.next();
//userInfo = new Water(size, weight, fish);
}
//creature.add(userInfo);
//System.out.println(user.displayCr());
}
I feel like I'm on the right path, but the last steps just aren't clicking for me and I've been grinding on this, reading, videos and nothing is clicking.
Also, I apologize if I've made the newbie mistakes in this post. I will accept all criticism, suggestions and help as a positive lesson. Thanks.
Overall your code is fairly right.
Except:
Creature userInfo = null; you are defining it inside the first IF, its scope will be limited to that IF.
As soon as you leave that IF it ceases to exist, hence you can't use it in the following IFs.
Consider the following scope change:
if(selection==1 || selection==2){ // main IF
Creature userInfo = null;
...
if(selection == 1){
...
}
else {
...
}
System.out.println(userInfo.displayCr());
} // end of main IF
First of all expand the scope of size,weight and userInfo means keep it inside main but outside the conditions as it is being used everywhere. Something like this.
int selection = 0;
String size = null;
String weight = null;
Creature userInfo = null;
Instead of this
creature.add(userInfo); should be
user.add(userInfo);
and call display like this
userInfo.displayCr(); because the return type of the method is void so cannot be used inside sysout and it should be inside that else if(){}
I've hit a wall on an assignment and have been combing the site for anything helpful (came up empty). I'm required to create a class, a constructor within that class, and then a subclass to extend the superclass. Then, I'm required to create a new file with a main method to demonstrate both cases. No problem, conceptually.
My question is this: how do I initialize an object using the constructor, but with user input?
Right now the error I'm getting is: "constructor CarRental in class CarRental cannot be applied to given types;
required: String,int,String,int
found: no arguments
reason: actual and formal argument lists differ in length"
Please no snide remarks on "the error tells you what the problem is." No, it doesn't tell me what it is. I'm a wee babe in this stuff and need a little hand-holding.
I'll paste my 3 classes below. They will probably make you writhe in agony, since I'm such a newb (also, my class is an abbreviated 8-week course where virtually no time was dedicated to pseudocode, so I have the extra challenge of conceiving the logic itself).
I am not looking for anyone to do my homework for me, I am just looking for a helping hand in the UseCarRental.java file. Here's my code..
public class CarRental {
protected String renterName;
protected int zipCode;
protected String carSize;
protected double dailyRate;
protected int rentalDays;
protected double totalCost;
final double ECONOMY = 29.99;
final double MIDSIZE = 38.99;
final double FULLSIZE = 43.50;
public CarRental(String renterName, int zipCode, String carSize, int rentalDays){
totalCost = dailyRate * rentalDays;
}
public String getRenterName(){
return renterName;
}
public void setRenterName(String renter){
renterName = renter;
}
public int getZipCode(){
return zipCode;
}
public void setZipCode(int zip){
zipCode = zip;
}
public String getCarSize(){
return carSize;
}
public void setCarSize(String size){
carSize = size;
}
public double getDailyRate(){
return dailyRate;
}
public void setDailyRate(double rate){
switch (getCarSize()) {
case "e":
rate = ECONOMY;
break;
case "m":
rate = MIDSIZE;
break;
case "f":
rate = FULLSIZE;
break;
}
}
public int getRentalDays(){
return rentalDays;
}
public void setRentalDays(int days){
rentalDays = days;
}
public double getTotalCost(){
return totalCost;
}
public void setTotalCost(double cost){
totalCost = cost;
}
public void displayRental(){
System.out.println("==============================================");
System.out.println("Renter Name: " + getRenterName());
System.out.println("Renter Zip Code: " + getZipCode());
System.out.println("Car size: " + getCarSize());
System.out.println("Daily rental cost: $" + getDailyRate());
System.out.println("Number of days: " + getRentalDays());
System.out.println("Total cost: $" + getTotalCost());
}
}
the subclass LuxuryCarRental....
public class LuxuryCarRental extends CarRental {
final double chauffeur = 200.00;
final double dailyRate = 79.99;
protected String chauffeurStatus;
public LuxuryCarRental(String renterName, int zipCode, String carSize, int rentalDays) {
super(renterName, zipCode, carSize, rentalDays);
}
public String getChauffeurStatus(){
return chauffeurStatus;
}
public void setChauffeurStatus(String driver){
chauffeurStatus = driver;
}
public double getChauffeurFee(){
return chauffeur;
}
public void setTotalLuxuryCost(){
if (chauffeurStatus=="y")
setTotalCost((dailyRate * getRentalDays()) + (chauffeur * getRentalDays()));
else
setTotalCost(dailyRate * getRentalDays());
}
#Override
public void displayRental(){
System.out.println("==============================================");
System.out.println("Renter Name: " + getRenterName());
System.out.println("Renter Zip Code: " + getZipCode());
System.out.println("Car size: " + getCarSize());
System.out.println("Optional Chauffeur fee: $" + getChauffeurFee());
System.out.println("Daily rental cost: $" + getDailyRate());
System.out.println("Number of days: " + getRentalDays());
System.out.println("Total cost: $" + getTotalCost());
}
}
and now the class with the main method:
import java.util.Scanner;
public class UseRentalCar {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
CarRental rentalCar = new CarRental();
System.out.println("==========================");
System.out.println("RENTAL CAR SELECTION");
System.out.println("==========================");
System.out.println("Enter your name: ");
rentalCar.setRenterName(keyboard.next());
System.out.println("Enter your zip code: ");
rentalCar.setZipCode(keyboard.nextInt());
System.out.println("Enter the car size ("e=Economy, m=Midsize, f=Fullsize: ");
rentalCar.setCarSize(keyboard.next());
System.out.println("Enter the number of days: ");
rentalCar.setRentalDays(keyboard.nextInt());
rentalCar.displayRental();
}
}
(omitted some cause it doesn't matter, mainly trying to get the object instantiation working)
thanks for any help!!
Create local variables in your main method, say String and int variables, and then after these variables have been filled with user input, use them to call a constructor.
I will post a general example, since this is homework, it is better to show you the concept and then let you use the concept to create the code:
public class Foo {
private String name;
private int value;
public Foo(String name, int value) {
this.name = name;
this.value = value;
}
}
elsewhere
import java.util.Scanner;
public class Bar {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter name: ");
String name = keyboard.nextLine(); // local variable
System.out.print("Please enter value: " );
int number = keyboard.nextint(); // another local variable
keyboard.nextLine(); // to handle the end of line characters
// use local variables in constructor call
Foo foo = new Foo(name, number);
}
The compiler is complaining that the CarRental constructor needs four parameters (a String, an int, a String, and another int):
"constructor CarRental in class CarRental cannot be applied to given types; required: String,int,String,int found: no arguments reason: actual and formal argument lists differ in length"
But in UseRentalCar, you haven't passed any:
CarRental rentalCar = new CarRental();
"constructor CarRental in class CarRental cannot be applied to given types; required: String,int,String,int found: no arguments reason: actual and formal argument lists differ in length"
If you don't provide a constructor for your class, Java will create a no-arg constuctor for you. If you provide your own (which you did in CarRental with 4 parameters), java will not create a no-arg constuctor, so you can't reference it. See http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html for more info on that.
You could add a no-arg constructor yourself since Java didn't do it for you. Or since you provide setters for your rental car classes, you could just use those like you are now, and remove your 4-arg constructor in CarRental (and LuxuryCarRental) and let Java add the default one.
Alternatively, if you want to keep those constructors for some reason, you could save the user input in local variables and defer the call to the 4-arg constructor until after you have all the user input.
"My question is this: how do I initialize an object using the constructor, but with user input?"
some psuedo-ish code that might help
main{
Scanner input = new Scanner(system.in);
int x = input.nextInt();
yourClass myClass = new yourClass(x); //passes x into the constructor
}//end main
yourClass
{
int data;
public yourClass(int i)
{
data = x:
}