Try-Catch statement Java - java

public void payForMeal(double amount) throws Exception {
if (balance - amount < 0 && amount - balance <= creditLimit) {
this.strStatus = "Using Credit";
double newBalance = balance - amount;
balance = newBalance;
throw new ArithmeticException("\n\n-----------------------------\n" + "You must top-up your balance\n" + "Your new balance is: " + balance + "\n" + "You are: " + strStatus + "\n" + "-----------------------------\n");
}//if
else if (amount > creditLimit && balance < amount) {
throw new ArithmeticException("\n\n----------------------\n" + "Cost of meal exceeds the credit limit." + "\n----------------------\n");
}//elseif
else {
double newBalance = balance - amount;
balance = newBalance;
transCount++;
}//else
}//payForMeal
when balance is 2 and payForMeal is set to 8 the following prints before the program crashes:
Displaying Account Details:
Cost of meal exceeds the credit limit.
Customer ID: 200
Name: Joe
Balance: 2.0
Minimum TopUp: 2.0
Account Status: Valid
Credit Limit: 5.0
Transaction Count: 0
How can I add a try-catch to stop the programming from crashing but still print out the errors, thanks

You should wrap the method which throws the error with the try catch, like so
// ... some code
try {
payForMeal(amount);
} catch (ArithmeticException e) {
System.out.log("An error occurred trying to pay for the meal: " + e.getMessage());
}
// ... more code
How you handle the error is for you to decide.

Try to do less in your methods. Programming is about problem decomposition and design.
Have a checkBalanceSufficient method that returns a result rather than doing this within your code. Check what kind of data it needs to return. Don't put in any print statements, that's for your main method or UI related classes & methods.
Don't reuse ArithmeticException. The calculations are fine, it is the result that you are not happy with. So you need to define your own higher level exception instead (programming an exception is really easy, just extend Exception). Preferably your code will never throw an exception due to problems with the input though; you can handle bad input within separate methods early in your code.
If there is any higher level code (i.e. code that implements a use case) within a catch clause then you are already doing things wrong.

Related

Java if...else statement not working properly

public double transferSavingToChecking(double Tamount2)
{
//check if enough to transfer
if(Tamount2 > Saving_Balance)
System.out.println("Transfer failed. You don't have enough balance in the saving account!");
else
System.out.println("You have successfully transferred $" + Tamount2 + " from the saving account to the checking account");
Saving_Balance = Saving_Balance - Tamount2;
Checking_Balance = Checking_Balance + Tamount2;
return Checking_Balance;
}
When money is transferred, the if...else statement runs through every time. For example, even when the transfer > balance, the output reflects that the transfer occurred anyways even when it says it failed.
You need to put curly braces around the content of your if/else blocks. If/else statements are written in the following way:
if (condition) {
// do something
} else {
// do something else
}
If you miss out the curly braces, only the first statement after the if/else is considered part of the if/else block.
Change your code to the following:
public double transferSavingToChecking(double Tamount2) {
//check if enough to transfer
if(Tamount2 > Saving_Balance) {
System.out.println("Transfer failed. You don't have enough balance in the saving account!");
} else {
System.out.println("You have successfully transferred $" + Tamount2 + " from the saving account to the checking account");
Saving_Balance=Saving_Balance - Tamount2;
Checking_Balance=Checking_Balance + Tamount2;
}
return Checking_Balance;
}

java loop logic issue

This feed method is supposed to first increase the energy state and decrease hungry state, use a dumplings meal (which can be purchased in the shop) then see that the item purchased from the shop, is a positive number or greater than 0. Then ensure that hungry and energy states do not go out of bounds (if it does print warning statements).
If it reaches the border of 100 then start increment overfeed, every time method is executed, if overfeed is greater than 4 then execute die method().
If it meets criteria running feed method will print Eating... and I have ate enough(...) statements.
#Override
protected void feed() {
decHungry(10);
incEnergy(10);
shop.useDumplingsMEAL();
do {
if (shop.dumplingsMEAL <= 0) {
JOptionPane.showMessageDialog(null, "You cannot eat right now, You need to purchase item in the shop");
}
else if (hungry <= 0 && energy >= 100) {
System.out.print("\nI have ate enough! My hungry state is " + hungry +
" and my energy state is " + energy + "." );
overfeed++;
while (overfeed>4)
{
die();
System.out.println("You have overfed me.");
}
}
else {
System.out.println("\nEating...");
System.out.println("I've just ate dumplings, my current energy state is " + energy
+" and hungry state is " + hungry + ".");
overfeed = 0;
}
}
You are calling a method called feed. This method looks like it should feed once if it can when it's called. Get rid of all the loops. If you want to keep it, read on do..while loop.
if(no food){
// nothing to feed
} else if (hunger level 0 or below & energy 100 or more){ // by the way hunger level should never go below 0 and energy should never go over 100
// increment overfeed
if(overfeed more than 4) {
// die
}
} else {
// feed
}
Just like the error message says, the syntax for do while is:
do {
// Do stuff
} while(some condition);
Also you seem to have some conditions that won't do what you want.
You are either having problem with your braces {} and indentation or don't understand properly how to use do-while loop.
Do-while should look like following:
do{
//making stuff
}
while(condition of loop);
At the moment your code looks like following:
do{
if(){
}
else{
while{
}
}
}

Reflection: Why are there methods like setAccessible()?

Just wondering, why did the people who invented Java write methods like setAccessible(boolean flag), which makes the access-modifiers (specially private) useless and cannot protect fields, methods, and constructors from being reached? Look at the following simple example:
public class BankAccount
{
private double balance = 100.0;
public boolean withdrawCash(double cash)
{
if(cash <= balance)
{
balance -= cash;
System.out.println("You have withdrawn " + cash + " dollars! The new balance is: " + balance);
return true;
}
else System.out.println("Sorry, your balance (" + balance + ") is less than what you have requested (" + cash + ")!");
return false;
}
}
import java.lang.reflect.Field;
public class Test
{
public static void main(String[] args) throws Exception
{
BankAccount myAccount = new BankAccount();
myAccount.withdrawCash(150);
Field f = BankAccount.class.getDeclaredFields()[0];
f.setAccessible(true);
f.set(myAccount, 1000000); // I am a millionaire now ;)
myAccount.withdrawCash(500000);
}
}
OUTPUT:
Sorry, your balance (100.0) is less than what you have requested
(150.0)! You have withdrawn 500000.0 dollars! The new balance is: 500000.0
Because some code is trusted code -- i.e., if a local application wants to do this, maybe it's not a big deal. For untrusted code, though -- i.e., an applet, or a web start application, or RMI stubs, or any other downloaded code -- there's a SecurityManager in place, which (generally based on a policy file) has the opportunity to say "Sorry, Charlie" and deny the setAccessible() request.
Well, once you have released a Java program, anyone is free to reverse engineer, or de-compile, it anyways, so if someone wanted it badly enough, they would probably be able to access your your "privates" anyway.
What you can do however, is to forbid any foreign code to access your stuff in your runtime. That is, if you're for instance using someone else's code you could disable reflections, access to files etc before those libraries are used.
Search for ClassLoader and Security Manager to find out more. Here's something that looks relevant.

Error with BigDecimal calculation regarding User Input

I have this idea for my assignment where I wanted a cash register system to calculate the total for an item when the user enters it's cost price and quantity of said item.
That seemed to work, but then led my main problem - I wanted to let the user type the letter "T" after say, 10 transactions, to find out the total takings for the day.
I tried to use a for loop with the BigDecimal math class within the calculations etc.
I have errors on the words 'valueOf' within my calculations & Eclipse keeps trying to change my values to 'long' & i'm pretty sure that's not right.
My explanation isnt amazing so i'll give you the code i wrote and place comments next to where my errors are ..
try{
Scanner in = new Scanner (System.in);
String t = "T";
int count;
for (count = 1;count<=10;count++){
System.out.println("\n\nValue of Item " + count + " :");
BigDecimal itemPrice = in.nextBigDecimal();
System.out.println("Quantity of item " + count + " :");
BigDecimal itemQuantity = in.nextBigDecimal();
BigDecimal itemTotal = (BigDecimal.valueOf(itemPrice).multiply // error here
(BigDecimal.valueOf(itemQuantity))); // error here
System.out.println("\nTotal for item(s): £" + itemTotal);
count++;
while (t == "T"){
BigDecimal amountOfItems = (BigDecimal.valueOf(itemTotal).divide // error here
(BigDecimal.valueOf(itemQuantity))); // error here
BigDecimal totalTakings = (BigDecimal.valueOf(itemTotal).multiply // error here
(BigDecimal.valueOf(amountOfItems))); // error here
System.out.println("The Total Takings For Today is £" + totalTakings + " " );
}
}
}
}
}
Like I said, the 'red lines' that eclipse uses to show there is an error are only under the words, "valueOf" within my BigDecimal calculations.
Any help would be great because i'm tearing my hair out !!!!
Thanx,
Vinnie.
There's no method BigDecimal.valueOf(BigDecimal). itemPrice and itemQuantity are already BigDecimal values - you don't need any conversion:
BigDecimal itemTotal = itemPrice.multiply(itemQuantity);
EDIT: Okay, so the above solves your immediate problem, but you've also got:
while (t == "T")
{
// Loop that never changes the value of t
}
There are two issues with this:
The loop will always either execute forever, not execute at all, or keep going until an exception is thrown, because the loop condition can never change as you're not changing the value of t. My guess is you want t = System.in.readLine() at some point...
You're comparing two string references here whereas I suspect you want to compare their values, e.g.
while (t.equals("T"))

Question safe withdraw/deposit using AspectJ

I have question regarding making a bankAccount class implement safe withdraw/deposit function. So far it will print log when you make a withdraw or deposit to the bankAccount class. Anyway my question is how to implement the safety e.g. you cannot withdraw more money than what you have currently in your bankAccount. If I'm not allowed to implement that safety in the bankAccount class, and want to implement it to an AspectJ.
I have the following now. As can be seen the withdraw is done regardless if the if-statement is true or false. Therefore I had to in the else statement deposit back the amount of money, so it would not turn negative. Can this be done in some nicer way possibly?
pointcut checking(BankAccount ba, float x):
call(* BankAccount.withdraw(..)) && target(ba) && args(x);
before(BankAccount b, float x) : checking(b, x) {
if(b.getBalance() >= x) {
System.out.println("Account changing. $" + x + " withdrawn...");
} else {
System.out.println("Account does not have. $" + x + " to withdrawn...");
b.deposit(x);
}
}
I'd say this would be better handled by an around advice, which can prevent proceeding to the normal invocation and substitute some other action instead if the transaction shouldn't be allowed.
The code for the around advice should be basically similar to what you wrote for before, except in the if block you'd have to call proceed to continue into the normal execution, and in the else block you'd no longer need the call to deposit.

Categories

Resources