Again, I am a java n00b and I am trying to learn from scratch and running into some embarrassing problems.
I got an Account class as follows:Account.java
public class Account
{
protected double balance;
// Constructor to initialize balance
public Account( double amount )
{
balance = amount;
}
// Overloaded constructor for empty balance
public Account()
{
balance = 0.0;
}
public void deposit( double amount )
{
balance += amount;
}
public double withdraw( double amount )
{
// See if amount can be withdrawn
if (balance >= amount)
{
balance -= amount;
return amount;
}
else
// Withdrawal not allowed
return 0.0;
}
public double getbalance()
{
return balance;
}
}
I am trying to use extends to inherit the methods and variables in this class. So, I used InterestBearingAccount.java
import Account;
class InterestBearingAccount extends Account
{
// Default interest rate of 7.95 percent (const)
private static double default_interest = 7.95;
// Current interest rate
private double interest_rate;
// Overloaded constructor accepting balance and an interest rate
public InterestBearingAccount( double amount, double interest)
{
balance = amount;
interest_rate = interest;
}
// Overloaded constructor accepting balance with a default interest rate
public InterestBearingAccount( double amount )
{
balance = amount;
interest_rate = default_interest;
}
// Overloaded constructor with empty balance and a default interest rate
public InterestBearingAccount()
{
balance = 0.0;
interest_rate = default_interest;
}
public void add_monthly_interest()
{
// Add interest to our account
balance = balance +
(balance * interest_rate / 100) / 12;
}
}
I get an error saying import error '.' expected when I try to compile. All the files are in the same folder.
I did javac -cp . InterestBearingAccount
If all the files are in the same folder / package, you don't need to do an import.
When you define your class you can optionally include a package statement at the top of the file. This mandates the package that the class belongs to and should correlate to its position on the file system. For example, a public class Account in package com.foo should be defined in the following file hierarchy:
com
|
|--foo
|
|--Account.java
As you have omitted the package statement both your classes belong to the anonymous package. For classes belonging to the same package there is no need to import classes in order to reference them; this is only a requirement for classes in a different package.
if you're classes are in the same package, it's not necessary to import. Otherwise you should import the package + the Class name.
make InterestBearingAccount class public, like
public class InterestBearingAccount {}
Related
I have two classes within a java project, one is the Employee1 class and the other is the info class. Within the Employee 1 class I have this code:
public class Employee1 {
String employeeName;
int hoursWorked;
double rateOfPay;
double wages;
public Employee1(String name, int hours, double pay) {
employeeName=name;
hoursWorked=hours;
rateOfPay=pay;
}
public String getName() {
return employeeName;
}
public void setName(String xName) {
employeeName = xName;
}
public double getHours() {
return hoursWorked;
}
public void setHours(int xHours) {
hoursWorked = xHours;
}
public double getPay() {
return rateOfPay;
}
public void setPay(double xPay) {
rateOfPay = xPay;
}
public double calculateWages () {
wages= hoursWorked * rateOfPay;
return wages;
}
public void print() {
System.out.println("name:"+ employeeName);
System.out.println("hours " + hoursWorked);
System.out.println("Wages Earned"+ wages);
}
}
Within my info class I have this code:
public class Info {
public static void main(String[] args) {
Employee1 x= new Employee1("Sarah",40,7.25);
Employee1 y=new Employee1("Bob",30,8.00);
Employee1 z= new Employee1("Todd",26, 8.25);
x.print();
}
}
My problem right now is that I am attempting to create a calculation for wages within my Employee1 class as you can see with my calculateWages method. However, whenever I call my print method for my existing employee x the wages always come out to be 0.0 and I am unsure why this is happening. I have preexisting variables for each of my Employee1 objects and I am still getting a 0.0 value for all of their wages but the rest of their information is printed correctly. Can anyone help me with this issue? Thank you!
In the code you provide there is not a setter method, instead there is a getter one. And yes, you can made calculation in both, getter and setter.
public void setAmount(int amount){
this.amount = quantity * price;
}
public void getAmount(){
return this.amount + otherProperty;
}
Lets start with this:
I'm new to programming but I know that this type of method is known as a setter.
No it isn't.
In OO, the code (mostly) consists of classes which consist of state (fields) and methods that (typically) operate on that state.
By convention ...
A setter is a method that sets a field to a new value provided as a method argument.
A getter is a method that returns the value of a field.
Your method is neither a setter or a (pure) getter:
It is not a setter because it doesn't set wages to a supplied value. (It is doing the calculation based on previously supplied values.)
You could view it as a getter for the wages field, but it is "impure" in that it updates the field as well as returning its value.
Every time I go to print out the "wages" variable it just gives me a zero and nothing else, I have the other variables hoursWorked & rateOfPay defined in the main
We cannot explain this without seeing the rest of your code. However, I suspect that the problem is one of the following:
Either of hoursWorked or rateOfPay is zero ... because they are not being correctly set / initialized to non-zero values.
The calculateWages method is not being called.
You have multiple instances of the class that defined this method ... and your code is looking at the wrong one.
Possibly ... some of the variables involved have been incorrectly declared as static.s
UPDATE - Now that I see your code, the reason that wages is zero is that your code doesn't call calculateWages.
You can pass those values to the calculateWages () method.
Try this
public double calculateWages (int hoursWorked, double rateOfPay) {
return hoursWorked * rateOfPay;
}
In the best practice of OOP your method should have two arguments:
e.g.
public class Answer1 {
public static double calculateWages (int hoursWorked, double rateOfPay){
return hoursWorked * rateOfPay;
}
public static void main(String[] args) {
System.out.println(calculateWages(6, 5.24));
}
}
You may want to simplify this by creating a class, outside of the main class with the main method, that does this ONE specific job of calculating a wage. We call this "isolation" in programming, and we want to isolate one class from another and make sure each class only does one particular job. Here is an example of a class that will get the total wage:
public class WagesCalc {
public static double calculateWages(int hoursWorked, double hourlyWage) {
double wage = (double)hoursWorked * hourlyWage;
return wage;
}
}
In the code above we can create a class that calculates the wages called WagesCalc. Within it, we can create a method called calculate wages. You can add hours worked, and the hourly wage as the arguments for the class. We then add a variable, and then return an the wage. We make this method static so that we can return it without an instance of the class being created. Here is the code in the main method:
public class App {
public static void main( String[] args )throws IOException{
double wages = WagesCalc.calculateWages(23, 23.50);
System.out.println("My total wage is $" + wages);
}
}
And here is the output:
My total wage is $540.5
i a beginner at java and I'm trying to compile 2 java codes Account.java and AccounTest.java and the command prompt keeps giving this message
"Main method not found in class Account, please define main method or a javaFX application class must extend javafx.application.Application"
researched on javafx apication and none was specific on what and where i should import. here is Account.java
"public class Account
private double balance;
public Account( double initialBalance )
{
if (initialBalance > 0.0)
balance = initialBalance;
}
public void credit( double amount)
{
balance = balance + amount;
}
public double getBalance()
{
return balance;
}
}
thanks in advance
So, I followed the online youtube tutorial for this, and it worked for the tutorial instructor, but not me... However, only because it wants a "getBalance" class in the source classes. If someone could help me with this, it would be greatly appreciated. I'm new to Java, and I do have some reading to catch up on in the book... So here's the program and its class setup:
BankAccountDemo.java
package bankaccountdemo;
import java.text.DecimalFormat;
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount account1 = new BankAccount(12.00);
BankAccount account2 = new BankAccount(account1);
DecimalFormat dollar = new DecimalFormat("#.##0.00");
System.out.print("The balance in account #1 is $" + dollar.format(account1.getBalance()));
System.out.print("The balance in account #2 is $" + dollar.format(account2.getBalance()));
}
}
BankAccount.java
package bankaccountdemo;
public class BankAccount {
private double balance;
public BankAccount() {
balance = 0.0;
}
public BankAccount(BankAccount obj) {
balance = obj.balance;
}
public BankAccount(double startBalance) {
balance = startBalance;
}
}
I am aware that this is a pretty simple fix, but as I said.. I have some reading to catch up on. I understood the lottery problem better than this very simple bug.
it wants a "getBalance" class in the source classes.
It doesn't want a class it wants a method that is called on your bankaccount object.
account1.getBalance()
So you need to create a method in your BankAccount class.
public double getBalance(){
return balance;
}
This function is called a getter function. In OOP languages an object's properties are usually created as private and can be modified/set and read/get using this setter and getter functions.
so you can create another function like
public void setBalance(double balance){
this.balance = balance;
}
and then you can use
account1.setBalance(10.0);
to set the amount to 10.0
As you said, you need a getBalance() method in BankAccount:
public double getBalance() {
return balance;
}
How can I make two objects of the same class use different interest rates?
I need to make it so that savingAccount2 and savingAccount3 use different interest rates.
savingAccount1UI savingAccount2 = new savingAccount1UI();
savingAccount1UI savingAccount3 = new savingAccount1UI();
These objects both inherit from a class called Account.java. This superclass contains all the methods that include how to calculate the interest.
Here is the current method in the superclass that calculates the 1 year interest account.java:
//add interest
public void interest(double interest){
if(balance<target){
interest = balance*lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*highRate;
balance = balance + interest;
}
updatebalance();
}
Here is the button that triggers this method:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
interest(Float.parseFloat(balanceLabel.getText().substring(1)));
Currently I am using variables with double values assigned to them, but of course this means that both objects(savingAccount2 and savingAccount3) use the same numbers. Note that these variables are stored in the Account.java superclass Like so:
public double lowRate = 0.019;
public double highRate = 0.025;
I think I may need to use a constructor for each object, with pre-set values to solve my issue but I don't understand how to implement that idea. Any suggestions?
You can write method in class Account to set the values of lowRate and highRate like:
public void setRates(double lr, double hr){
lowRate=lr;
highRate=hr;
}
Now when you create an object of class SavingsAccount, you can do:
SavingsAccount sa=new SavingsAccount();
sa.setRates(0.019,0.025);
Just do it:
savingAccount1UI savingAccount2 = new savingAccount1UI(0.019,0.025);
in class definition:
savingAccount1UI(float lowRate,float highRate) {
this.lowRate = lowRate;
this.highRate = highRate;
}
when computing pass also the class to the method and access the inners value.
public void interest(double interest,savingAccount1UI account){
if(balance<target){
interest = balance*account.lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*account.highRate;
balance = balance + interest;
}
updatebalance();
}
It seems you are looking for this:
public class Account {
private double lowRate;
private double highRate;
//other fields
public Acount(double lowRate, double highRate) {
this.lowRate = lowRate;
this.highRate = highRate;
}
// your interest() method
// getters & setters
}
public class SavingAccount1UI extends Account {
public SavingAccount1UI(double lowRate, double highRate) {
super(lowRate, highRate);
}
// rest of your stuff
}
This way you are only able to create an object passing the values you need, like:
SavingAccount1UI savingAccount = new SavingAccount1UI(0.019, 0.025);
Now every time you call your interest() method, it will take into consideration the values passed.
Need help with my school work, I'm very much new to programming. So the requirements are:
Class Account, change the visibility of all data to protected. Change the withdraw method so that it becomes an abstract method. This action will necessitate you declaring the class as abstract. Deposits should work the same way in OnLineAccount and SavingsAccount so make sure they cannot override their parent’s version.
The OnLineAccount class has one additional attribute to that of class Account, minimumBalance. All instances of OnLineAccount are created with the minimumBalance amount set to $500. If transactions of any OnLineAccount cause the balance to go below minimumBalance, a $25 fee is subtracted from the account balance. Override the toString method to display everything the Account toString displays plus a message dependent upon the balance. If the balance is below the minimumBalance, a message stating that a $25 fee has been already been subtracted needs to alert the customer. Use the parent class toString to do most of the work.
The SavingsAccount class has one additional attribute to that of class Account, overdraft. All instances of SavingsAccount are created with the overdraft amount set to -$1000. An overdraft amount is the amount an object of SavingsAccount class may allow the balance to go to. Implement the withdraw method so that overdrafts are allowed up to the amount stored in overdraft. Any withdrawals that allow the balance to drop below zero and up to the overdraft amount are allowed but the overdraft fee of $30 is incurred each time a transaction causes the balance to be below zero.
Override the toString method to display everything the Account toString
displays plus a message dependent upon the balance. If the balance is below zero, a message stating that the person is in overdraft and a $30 fee has been already been incurred. Use the parent class toString to do most of the work.
Create a driver class with an array of 5 objects of Account, being some instances of the child classes OnLineAccount or SavingsAccount. Systematically test the full functionality of both child classes.
================================
So I created 4 class file, it shows all account info but also showing negative balance which should be an error message instead cause balance should not be less than $500.
Here are my class files:
Account class:
import java.text.NumberFormat;
import java.util.Locale;
public abstract class Account {
private static int defaultAccountNo = 12345;
protected String owner;
protected int accountNo;
protected double balance;
protected Account(String owner, double intialDeposit){
this.owner = owner;
this.balance = intialDeposit;
defaultAccountNo++;
this.accountNo = defaultAccountNo;
}
public final boolean deposit(double amount){
if(amount<=0){
System.err.println("Negative amount can't be deposited");
return false;
}
balance = balance+amount;
return true;
}
protected abstract boolean withdrawl(double amount);
public String getBalance(){
return formatter.format(balance);
}
public int getAccountNo(){
return accountNo;
}
public void setOwner(String owner){
this.owner = owner;
}
protected void addInterest(){
double interest = 0.05*balance;
balance = balance+interest;
}
public boolean equals(Account account){
if(this.owner.equalsIgnoreCase(account.owner))
return true;
else
return false;
}
NumberFormat formatter = NumberFormat.getCurrencyInstance();
public String toString(){
return "AccountNo: "+accountNo+"\nBalance: "+formatter.format(balance);
}
}
OnlineAccount Class:
public class OnLineAccount extends Account{
public OnLineAccount(String owner, double intialDeposit) {
super(owner, intialDeposit);
}
private static final double MINIMUM_BALANCE = 500;
public boolean withdrawl(double amount){
if(amount<0){
System.err.println("Negative amount cannot be withdrawn");
return false;
}
if((balance-amount)<0){
System.err.println("Not enought balance");
return false;
}
balance = balance-amount;
if(balance<MINIMUM_BALANCE)
balance = balance - 25;
return true;
}
public String toString(){
String returnString;
if(balance<500){
returnString = super.toString()+"\n$25 fee has been already been subtracted as account balance reached below minimum";
return returnString;
}
return super.toString();
}
}
SavingsAccount Class:
public class SavingsAccount extends Account{
private static final double DEFAULT_OVERDRAFT = -1000;
public SavingsAccount(String owner, double intialDeposit) {
super(owner, intialDeposit);
}
public boolean withdrawl(double amount) {
if(amount<0){
System.err.println("Negative amount cannot be withdrawn");
return false;
}
if((balance-amount-30)<DEFAULT_OVERDRAFT){
System.err.println("Not enough balance, overdraft reached");
}
if((balance-amount)<0){
balance = balance-amount-30;
return true;
}
return false;
}
public String toString(){
String returnString;
if(balance<500){
returnString = super.toString()+"\nYour are in overdraft and $30 fee has been already been subtracted.";
return returnString;
}
return super.toString();
}
}
TestAccount Class:
import java.util.Random;
public class TestAccount {
public static void main(String[] args) {
Random ran = new Random();
Account[] accountArray = new Account[5];
Account acc1 = new OnLineAccount("Bill", 1000);
Account acc2 = new OnLineAccount("Susan", 1500);
Account acc3 = new SavingsAccount("William", 2500);
Account acc4 = new SavingsAccount("Bill", 9000);
Account acc5 = new SavingsAccount("Bruce", 1355);
accountArray[0] = acc1;
accountArray[1] = acc2;
accountArray[2] = acc3;
accountArray[3] = acc4;
accountArray[4] = acc5;
for(int i=0; i<accountArray.length; i++){
System.out.println("Initial details of Account....");
System.out.println(accountArray[i]);
System.out.println("After some transactions..");
accountArray[i].deposit(ran.nextInt(300));
accountArray[i].withdrawl(ran.nextInt(3000
));
System.out.println("Balance: "+accountArray[i].getBalance());
System.out.println("After adding the interest for the year....");
accountArray[i].addInterest();
System.out.println("Balance: "+accountArray[i].getBalance());
System.out.println(); // for blank line
}
System.out.println("Checking for Duplicates now....");
for(int i=0; i<accountArray.length; i++){
for(int j=0; j<i; j++){
if(accountArray[i].equals(accountArray[j])){
System.out.println("Account "+accountArray[i].getAccountNo()+
" and "+accountArray[j].getAccountNo()+" are duplicates");
}
}
}
}
}
I spent hours with no luck. Any help would be much appreciated. Thanks.
This is my first post here.
The output I'm getting is (Account no 12350 is getting negative balance...):
Negative amounts are possibile in your code.
Imagine this scenario with an online account.
Robert has 3000 dollars. He withdraws 2990 dollars. There are only 10 dollars remaing.
Seeing that 10 dollars is less than the minimum amount, you subract 25 dollars.
So Robert will have -15 dollars on his account.
Thanks guys for your help. It's now working perfectly with all error messages showing up. I added toString() after getBalance() as J Richard Snape suggested and all OK now.
As Richard said, getBalance() was bypassing all warning.
Output now:
Negative amounts are possible because you have a bound that is higher than some of the person's initial amount deposited.
With the deposit and withdrawal in your block of code, you can withdraw into an amount that causes the person to have a balance in the negative.
accountArray[i].withdrawl(ran.nextInt(3000
));