Exception Error in Java : How to continue? - java

Now, here' the problem :
How to add exceptions so that if my value is negative it would return an error.
here's my current code.
public class Account {
String name;
double balance;
public Account()
{
super();
this.name = null;
this.balance = 0;
}
public Account(String n, double b){
name = n;
balance = b;
}
}
did I do things right? so far?
edited to shorten.

1 . Create new Exception class like NegativeBalanceException
2 . Validate balance from the place where you are calling Account(String n, double b). If its -ve then throw NegativeBalanceException and right a catch block to handle it

In my opinion, this is what the exercise wants you to do:
public class Account {
/*
* If you know about private members, declare them private.
* Probably you should because the exercise asks for getter and setter.
*/
/* private */ String name;
/* private */ double balance;
public Account() {
// Useless: Java calls automatically the superclass constructor.
// super();
/*
* These are useless too, because Java initializes the class
* members to 0, false and null.
* However, this is what the exercise is asking you to do.
*/
name = null;
balance = 0;
}
public Account(String name, double balance) {
// take advantage of setters
setName(name);
setBalance(balance);
}
public void setName(String name) { this.name = name; }
public void setBalance(double balance) {
if (balance < 0)
throw new IllegalArgumentException("balance must be non-negative.");
this.balance = balance;
}
public String getName() { return name; }
public double getBalance() { return balance; }
}

You don't need to call super(); in your default constructor since you don't have superclass defined (at least I don't see that it extends something) and this method will call constructor from superclass.

Related

Constructor and classes in Java

I have one class Account (abstract).
I have one class SavingsAccount (inherits Account).
I have one class CreditAccount (inherints Account).
SavingsAccount and CreditAccount are similar, except CreditAccount has a credit limit (variable limit).
I have the following problems:
I need help with how constructor in CreditAccount looks like. How can I add local variable limit to the constructor?
Is it better (easier) if I have a variable limit in base class instead, and let SavingsAccount Always set it to be zero, while CreditAccount let the user set the limit?
My teacher says since SavingsAccount and CreditAccount are almost the same, #Override are exactly the same, he recommends me to implement those methods in base class (Account). How will the code look like if I do that?
Thank you for your help
class Account:
public abstract class Account {
protected double balance = 0;
protected String accountId;
protected double interest = 0;
public Account() {}
public Account(double bal, String id, double inte) {
if (balance >= 0) {
balance = bal;
}
else {
balance = 0;
}
accountId = id;
interest = inte;
}
public abstract String getAccountId();
public abstract double getBalance();
public abstract double getInterest();
}
class SavingsAccount:
public class SavingsAccount extends Account {
public SavingsAccount() {
super();
}
public SavingsAccount(double bal, String id, double inte) {
super(bal, id, inte);
}
#Override
public String getAccountId() {
return accountId;
}
#Override
public double getInterest() {
return interest;
}
#Override
public double getBalance() {
return balance;
}
}
Class CreditAccount:
class CreditAccount extends Account {
private int limit;
public CreditAccount() {
super();
}
public CreditAccount(double bal, String id, double inte) { //How can I add local variable limit to this???
super(bal, id, inte);
}
public void setLimit(int limit) {
this.limit = limit;
}
#Override
public String getAccountId() {
return accountId;
}
#Override
public double getInterest(){
return interest;
}
#Override
public double getBalance() {
return balance;
}
}
in main:
System.out.print("Savings or Credit (S/C): ");
answer = input.next();
if (null != answer) switch (answer) {
case "S":
case "s":{
System.out.print("Amount to deposit: ");
double amount = input.nextDouble();
System.out.print("Interest: ");
double interest = input.nextDouble();
SavingsAccount savingsAccount = new SavingsAccount(amount, accountId, interest);
newCustomer.addAccount(savingsAccount);
bank.addCustomer(newCustomer);
break;
}
case "C":
case "c":{
System.out.print("Amount to deposit: ");
double amount = input.nextDouble();
System.out.println("Interest: ");
double interest = input.nextDouble();
CreditAccount creditAccount = new CreditAccount(amount, accountId, interest);
newCustomer.addAccount(creditAccount);
bank.addCustomer(newCustomer);
break;
}
default:
System.out.println("invalid answer");
break;
}
To answer your questions without giving your assignment away...
1) I need help with how constructor in CreditAccount looks like. How can I add local variable limit to the constructor?
I suppose you're confused about "having" to implement the constructor of the base. Well, that doesn't prevent you from providing one specific to the needs of the sub.
public CreditAccount(..., double limit) {
//call the super from this
this.limit = limit;
}
Is it better (easier) if I have a variable limit in base class instead, and let SavingsAccount Always set it to be zero, while CreditAccount let the user set the limit?
Better; nope. Easier; that's subjective. Is it easier to set an untold number of sub class' needless variable easier than not including it in the first place?
Easier isn't a factor that overrides good design. The whole point of all this is providing nice little data holders void of clutter. On top of that, it just doesn't seem right; does it; what does your gut say?
My teacher says since SavingsAccount and CreditAccount are almost the same, #Override are exactly the same, he recommends me to implement those methods in base class (Account). How will the code look like if I do that?
As opposed to the abstract class leaving the methods unimplemented, implement them. Put the simple getters inside the abstract class and remove them from the subs. The resulting code would look something like...
public CreditAccount ... {
protected double limit;
//those constructors you need
public double getLimit() { ... }
}
...for starters.

Inheritance & Polymorphism in Java

I have programmed for exercising the Inheritance & Polymorphism use in Java, but coming across some problems, please see the codes below:
Superclass:
public class Worker {
private String name;
private double salaryRate;
public Worker(String nm, double rate){
nm=name;
rate=salaryRate;
}
public void computePay(int hours){
double pay=hours*salaryRate;
System.out.println("The Salary for "+getName()+" is "+pay);
}
public String toString(){
return name+" "+salaryRate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalaryRate() {
return salaryRate;
}
public void setSalaryRate(double salaryRate) {
this.salaryRate = salaryRate;
}
}
one subclass:
public class HourlyWorker extends Worker {
public HourlyWorker(String nm, double rate) {
super(nm, rate);
}
public void computePay(int hours){
if (hours>40){
double extraPay=(hours-40)*1.5*getSalaryRate();
double pay=40*getSalaryRate();
double total=extraPay+pay;
System.out.println("The salary for "+getName()+" is "+total);
}
else{
super.computePay(hours);
}
}
}
Another subclass:
public class SalariedWorker extends Worker {
public SalariedWorker(String nm, double rate){
super(nm,rate);
}
public void computePay(int hours){
double pay=40*getSalaryRate();
System.out.println("The salary for "+getName()+" is "+pay);
}
}
Main() method:
public class Test {
public static void main(String[] args) {
Worker a=new HourlyWorker("Tom",2.0);
Worker b=new HourlyWorker("Lee",2.0);
Worker c=new SalariedWorker("Pei",2.0);
Worker d=new SalariedWorker("Joe",2.0);
System.out.println(a+" "+b+" "+c+" "+" "+d);
a.computePay(50);
b.computePay(30);
c.computePay(20);
d.computePay(60);
}
}
It is a bit long, thank you for your patient to read:)
However, when they compile, it shows:
null 0.0 null 0.0 null 0.0 null 0.0
The salary for null is 0.0
The Salary for null is 0.0
The salary for null is 0.0
The salary for null is 0.0
Please advise where goes wrong, thank you guys!
You assignments are reversed in the constructor. You are not setting the instance attributes values using the input params and hence those attributes always have the default values.Change this
public Worker(String nm, double rate){
nm=name;
rate=salaryRate;
}
to
public Worker(String nm, double rate){
this.name=nm;
this.salaryRate=rate;
}
Note: Usage of this helps you to avoid shadowing problems as well when the name of the input params and class attributes are same.
public Worker(String nm, double rate){
nm=name;
rate=salaryRate;
}
you are assigning values to local variables not to the instance variables.
Therefore those variables are having their default values.
for string default value is null
for double it is 0.0
you should do
public Worker(String nm, double rate){
name = nm;
salaryRate = rate;
}

Error when applying values to an object

I need some help with this java code, i seem to get stuck at the object vara var = new vara("banan","12.5","5"). I thought since i created a constructor in class vara with three arguments String,double and int it would be fine to call for them in the test class and get the result i want but i get an error stating that constructor vara in class vara cannot be applied to given types. And it says it requires a string, a double and an int. But i have provided these so what is the problem?? id be thankful for any kind of help, im stuck with this for 4 days now and i just cant see any light in the tunnel.
import java.lang.String;
public class Vara {
//Deklarerar variabler
private String name;
private double price;
private int antal;
//tildela konstruktorer för de deklarerade variablerna
public Vara (String name, int antal, double price) {
this.name = name;
this.antal = antal;
this.price = price;
} // slut constructor
public void setName(String name) {
this.name = name; }
public void setPrice (double price) {
this.price = price; }
public void setAntal (int antal) {
this.antal = antal; }
public String getName() {
return this.name;}
public double getPrice() {
return this.price; }
public int getAntal() {
return this.antal; }
}
//testklassen ska stå som en egen klass
class Test {
public void main(String[] args){
}
Vara var = new Vara("Banan","12.5","5") {
#Override
public void setName(String name) {
var.setName("Banan");
}
#Override
public void setPrice (double price) {
var.setPrice("12.5");
}
#Override
public void setAntal (int antal) {
var.setAntal("5");
System.out.println("Namnet är " +var.getName() +" priset är " +var.getPrice() +" och antalet är "+var.getAntal() );// här slutar system.out
}// slut main
}
// slut Test klass
You are invoking the constructor with wrong parameters :
Vara var = new Vara("Banan","12.5","5")
is not what your constructor expects :
public Vara (String name, int antal, double price)
You are passing three String literal to the constructor when it expects a String,int,double in specified order. Anything enclosed in "" is a String literal.
Replace with :
Vara var = new Vara("Banan",5,12.5);
"Banan" ---> It is a String literal.
12.5 ---> double by default , 12.5f is float.
5 ---> int by default , 5l is long.
You need to do the same thing while invoking the setter methods.
Please note that you are calling your constructor with 3 String parameters:
Vara var = new Vara("banan", "12.5", "5");
As you have only defined a constructor which takes a String, an int and a double you have to remove the quotation marks:
Vara var = new Vara("banan", 12.5, 5);
Also this will not work as you now supply a double to the int parameter and vice versa. So either you have to change your constructor to
public Vara (String name, double price, int antal)
or change your call to
Vara var = new Vara("banan", 5, 12.5);
Remove the double quotes from the last two arguments to constructor:
Vara var = new Vara("Banan",5,12.5);
Reason: If you enclose between double quotes then it is treated as String by Java and not double or int. And as your constructor does not accept three String arguments it gives error.
Same is the issue with the setter methods that you are calling on the var object.
the setAntal(int antal) needs an int argument but you are passing String. Hence remove double quotes while calling setter method too.
var.setAntal(5);
var.setPrice(12.5);
Also when you send the tree arguments to the constructor, then you do not need to call the setter method for setting the same values again.
Running Code:
public class Vara {
//Deklarerar variabler
private String name;
private double price;
private int antal;
//tildela konstruktorer för de deklarerade variablerna
public Vara (String name, int antal, double price) {
this.name = name;
this.antal = antal;
this.price = price;
} // slut constructor
public void setName(String name) {
this.name = name; }
public void setPrice (double price) {
this.price = price; }
public void setAntal (int antal) {
this.antal = antal; }
public String getName() {
return this.name;}
public double getPrice() {
return this.price; }
public int getAntal() {
return this.antal; }
}
//testklassen ska stå som en egen klass
class Test {
public static void main(String[] args){
Vara var = new Vara("Banan",5, 12.5);
System.out.println("Namnet är " +var.getName() +" priset är " +var.getPrice() +" och antalet är "+var.getAntal() );// här slutar system.out
}
}
To point out some errors:
Your main method must be static
main method ended as soon as it starts and code must be inside the main method.
For others compare my code with yours. I would recommend you to see some basic java tutorials.
As you declared constructor of the class as public Vara (String name, int antal, double price) , so at you should call create an object of this class is as follow
Vara var = new Vara("Banan",5,12.5);

Why will objects now be created from my class

An error points to the word "new" when I try to compile this program. I'm trying to create 2 objects from the carOrder class and I'm havin troubles! I've had this problem with other programs before and I'm not sure why and it's killing me, please help!
import java.text.DecimalFormat;
import java.util.Scanner;
public class CarOrder
private String buyer;
private String carType;
private double cost;
private int quantity;
private boolean taxStatus;
private double discountedCost;
private double taxAmount;
// Default Constructor
public void carOrder()
{
}
// Constructor
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
buyer = buy;
carType = car;
cost = cos;
quantity = quan;
taxStatus = tax;
}
// Sets the company buying cars
public void setBuyer(String buy)
{
buyer = buy;
}
// Sets the car type being purchased
public void setCarType(String car)
{
carType = car;
}
// Sets cost of the cars being purchased
public void setCost(double cos)
{
cost = cos;
}
// Sets the quantity of cars being purchased
public void setQuantity(int quan)
{
quantity = quan;
}
// Sets tax status for the cars
public void setTaxStatus(boolean tax)
{
taxStatus = tax;
}
// Returns name of buyer to user
public String getBuyer()
{
return buyer;
}
// Returns type of car to user
public String getCarType()
{
return carType;
}
// Returns cost to user
public double getCost()
{
return cost;
}
// Returns quantity of cars to user
public int getQuantity()
{
return quantity;
}
// Returns tax status to user
public boolean getTaxStatus()
{
return taxStatus;
}
// Returns discounted cost to user
public double getDiscountedCost()
{
if (quantity > 10)
if (quantity > 20)
discountedCost = cost - cost * .10;
else
discountedCost = cost - cost * .05;
else
discountedCost = cost;
return discountedCost;
}
// Returns tax amount to users
public double getTaxAmount()
{
taxAmount = cost * .0625;
return taxAmount;
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
CarOrder speedy = new CarOrder("Speedy Rental", "Mini Cooper", 22150, 15, true);
CarOrder zip = new CarOrder("Zip Car Co.", "Ford Fusion", 27495, 6, true);
System.out.println("Enter first Buyer");
String buyer1 = keyboard.nextLine();
}
}
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
should be
public CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
Constructor's don't have a return type, not even void.
Currently, you have a method named CarOrder in your class as it has a return type as void, which voilates the rules of custructor. If you remove void, then it'd a constructor as it has the same name as your class.
Same applies to your constructor with no-argsaswell.
public void CarOrder()
should be
public CarOrder()
you are missing a "{" right after public class CarOrder ... :)
When you don't declare a constructor, Java provides a default constructor that have no arguments. As you declared CarOrder(String buy, String car, double cos, int quan, boolean tax), the default constructor is not created anymore. You made a method called carOrder, that probably was an attempt to make a constructor with no arguments, but it has two problems:
it has a return type (void) and constructor doesn't have one
the name is different from the class (cardOrder isn't the same as CarOrder, since Java is case sensitive)
If you want to make a new CarOrder() call, just add the following code:
public CarOrder() {
//insert your implementation here
}
A constructor with a return type is treated as a method by the compiler.

Method Retrieval and Inheritance Confusion

Ok,so I am getting a lot of trouble, I am still learning Java and my book has set me a task that I find common over the net, the part that I am stuck on is...
I must create a bank account program, an account holder is given a savings account (which has an interest rate and no overdraft facility), and a checking account (which has an overfraft facility of £100 and no interest).
I am not implementing the overdraft yet and am only half way to getting the withdraw and deposit function ready but my question is with the interest, I have defined in my superclass the savings account balance and the checking account balance so when working out my interest in the savings account class I cannot reference savebalance as I have made it private. I am trying to use the set.name method but i am clearly doing it wrong....
A big smile and a thank you for any one who can help or give advice!
Superclass is as follows:
public class BankDetails
{
private String customer;
private String accountno;
private double savebalance;
private double checkbalance;
//Constructor Methods
public BankDetails(String customerIn, String accountnoIn, double savebalanceIn, double checkbalanceIn)
{
customer = customerIn;
accountno = accountnoIn;
savebalance = savebalanceIn;
checkbalance = checkbalanceIn;
}
// Get name
public String getcustomername()
{
return (customer);
}
// Get account number
public String getaccountnumber()
{
return (accountno);
}
public double getcheckbalanceamount()
{
return (checkbalance);
}
public double getsavebalanceamount()
{
return (savebalance);
}
public void savewithdraw(double savewithdrawAmountIn)
{
savebalance = savebalance - savewithdrawAmountIn;
}
public void checkwithdraw(double checkwithdrawAmountIn)
{
checkbalance = checkbalance - checkwithdrawAmountIn;
}
public void savedeposit(double savedepositAmountIn)
{
savebalance = savebalance - savedepositAmountIn;
}
public void checkdeposit(double checkdepositAmountIn)
{
checkbalance = checkbalance - checkdepositAmountIn;
}
} // End Class BankDetails
Sub Class is as follows:
import java.util.*;
public class Savings extends BankDetails
{
private String saveaccount;
private double interest;
public Savings(String customerIn, String accountnoIn, float interestIn,
String saveaccountIn, double savebalanceIn)
{
super (customerIn, accountnoIn, savebalanceIn, interestIn);
saveaccount = saveaccountIn;
interest = interestIn;
}
public String getsaveaccountno()
{
return (saveaccount);
}
public double getinterestamount()
{
return (interest);
}
public void interestamount(String[] args)
{
BankDetails.getsavebalanceamount(savebalance);
interest = (savebalance / 100) * 1.75;
}
}
Use the superclass's getSaveBalance() method to access the balance (which is suspiciously-named, since you have a savings account class, but keep the balance elsewhere).
(Currently it's getsavebalanceamount(), I assume a renaming to keep with Java conventions.)
I'd recommend using consistent CamelCase when naming your getters and setters, e.g., getInterestAmount(), getSaveAccountNo(), etc.
I recommend against commenting simple getters/setters, but if you do, use Javadoc conventions, e.g.:
/** Returns current savings account balance. */
public double getSaveBalance() { ... etc ... }
I also recommend avoid unnecessary parentheses, as currently in your getters, e.g.:
public double getSaveBalance() {
return saveBalance; // No parens required.
}
I suggest you do something like this,
interface Account{
int getAccountNumber();
float getBalance();
}
public class SavingAccount implements Account, Interest{
int accountNumber;
public int getAccountNumber(){
return accountNumber;
}
float balance;
public float getBalance(){
return balance;
}
float savingInterestRate;
public float getInterestRate(){
return savingInterestRate;
}
}
public class CheckingAccount implements Account, OverDraft{
int accountNumber;
public int getAccountNumber(){
return accountNumber;
}
float balance;
public float getBalance(){
return balance;
}
}
interface Interest{
float getInterestRate();
}
interface OverDraft{
....
}

Categories

Resources