Java if...else statement not working properly - java

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;
}

Related

Try-Catch statement 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.

Removing a number from a listed created by given numbers

so here's the details.
I'm coding using java - BlueJ, and currently have a main class Auction, and a few other classes: Lot, Person, Bid
The purpose of the program is to enter items into the auction, along with their prices, where the information will be stored according to whether it's price, person, or item name/description.
This is the code for my getLot method - user inputs lot number, and it shows info for the lot, which I assume should also be the starting point for the removeLot method since it should still check if the lot number given is valid first.
I'm trying to figure out how to add a removeLot method so that I can remove an item from the lot by typing in its lot number.
This is the code I have for that section.
public Lot removeLot(int number)
{
if((number >= 1) && (number < nextLotNumber)) {
// The number seems to be reasonable.
Lot selectedLot = lots.get(number - 1);
// Include a confidence check to be sure we have the
// right lot.
if(selectedLot.getNumber() != number) {
System.out.println("Internal error: Lot number " +
selectedLot.getNumber() +
" was returned instead of " +
number);
// Don't return an invalid lot.
selectedLot = null;
}
**else {
Lot.removeIf(selectedLot.getNumber() = number);**
}
return selectedLot;
The else block with the "**" is what I added, wanting to remove the given number. But it's clearly wrong, and I'm not sure what to do.
If the datatype of lots variable is List than you can try below code
public Lot removeLot(int number)
{
Lot selectedLot=null;
if((number >= 1) && (number < nextLotNumber)) {
// The number seems to be reasonable.
selectedLot = lots.get(number - 1);
// Include a confidence check to be sure we have the
// right lot.
if(selectedLot.getNumber() != number) {
System.out.println("Internal error: Lot number " +
selectedLot.getNumber() +
" was returned instead of " +
number);
// Don't return an invalid lot.
selectedLot=null;
}
else {
if(selectedLot.getNumber() = number)
{
lots.remove(number-1);
}
}
return selectedLot;
}
Lot.removeIf(selectedLot.getNumber() = number) is not correct
you can try:
} else if(selectedLot.getNumber() == number) {
Lot.removeIf(selectedLot.getNumber());
}

Improving methods in Java

I have recently started a course where the main language we are learning at the moment is Java.
I have been tasked with creating a program that allows people to vote on two candidates - the program then counts the votes, and depending on how man votes have been made depends on what is displayed.
Here is the part I am concerned with at the moment:
public String printResults(){
if(candidate1Votes == 0 && candidate2Votes == 0)
{
System.out.println ("No votes cast, results cannot be displayed.");
return "No votes cast, results cannot be displayed.";
}
else if(this.completed == false)
{
System.out.println ("Voting has not finished");
return "Voting has not finished";
}
else if(this.completed == true)
{
System.out.println ("Voting has finished, no more votes will be allowed.");
return "Voting has finished, no more votes will be allowed";
}
{
double totalVotes = this.candidate1Votes + this.candidate2Votes;
double cand1Share = (double) this.candidate1Votes/totalVotes*100;
double cand2Share = (double) this.candidate2Votes/totalVotes*100;
System.out.format(candidate1 + " received %3.1f percent of the votes\n", cand1Share);
System.out.format(candidate2 + " received %3.1f percent of the votes\n", cand2Share);
return "v";
}
}
Originally I used void in this method, but part of our task was to then change it to a string value. This is where I am struggling - once I set completed to true, it is still allowing me to cast votes. I know that this code is incomplete but I can't finish it as I am unsure what to do! These were the next parts to the questions.
Modify your printResults method so that it applies the first two rules. Note that the value of the completed field indicates whether or not voting is complete. The method should be modified to return a String which indicates whether printing has been successful.
Modify your vote method to apply the third rule.
Test your methods by creating an instance and doing the following – before
doing each test note the result you expect to get, and compare this with what you actually get:
• Try to print results immediately
• Cast votes for both candidates and try to print results
• Set the completed field to true by calling setCompleted
• Try to cast a vote for a candidate
• Print the results
I am new to this (this is my first year) and have managed to do okay in my books to get this far, however any help on this next issue would be greatly appreciated!
First of your code is unnecessary complicated, which makes it hard to read/enhance. It can easily simplified, like
public String printResults(){
if(candidate1Votes == 0 && candidate2Votes == 0) {
System.out.println ("No votes cast, results cannot be displayed.");
return "No votes cast, results cannot be displayed.";
} // you returned ... NO need for ELSE!
if(this.completed == false) {
System.out.println ("Voting has not finished");
return "Voting has not finished";
}
// it is very clear here that completed must be true!
double totalVotes = this.candidate1Votes + this.candidate2Votes;
double cand1Share = (double) this.candidate1Votes/totalVotes*100;
double cand2Share = (double) this.candidate2Votes/totalVotes*100;
System.out.format(candidate1 + " received %3.1f percent of the votes\n", cand1Share);
System.out.format(candidate2 + " received %3.1f percent of the votes\n", cand2Share);
return "v";
}
Probably that easier-to-read code is all that you need to get you going!
Looking at the code the last block will never be reached because either you have no votes or you have votes and in that case completed will be either true or false and will thus reach always one of the else ifs and they all return a string. So I wonder why how you can cast any votes at all.
You could also post the code where you call printResults and setCompleted to see where the problem lies.
Some more hints for improving your code:
Sometimes you have the opening bracket on the same line and sometimes on the next. You should probably choose one style
It is not necessary to surround the last code block with brackets
if (this.completed == true) and else if (this.completed == false) is a bit redundant and can be written like: if (this.completed) and if (!this.completed). Also you can write
if (this.completed) {
...
} else {
....
}
because if completed is not true it can only be false.
Instead of writing every String two times and having to edit it two times in case you want to change something you could also do the following:
String msg = "Voting has not finished"
System.out.println(msg);
return msg;

How do I get out of this freaking loop

I understand that while the state is true the loop will keep running. I thought if I simply typed in loop=false, after the } bracket for the loop I could continue to code. Obviously I was wrong, it wont run anything. SOMEONE please show me how to get out of this hell of a while loop.
System.out.println("You total balance is 0.00, "
+ "please deposit coins and type done when finished");
while(loop){
if (input.hasNextInt()){
deposit = input.nextBigDecimal();}
String change = input.next();
switch (change){
case "quarter":
balance= quarter.multiply(deposit);
total=total.add(balance);
System.out.println("Your balance is "+ total +" :Make addiontal deposit(s)");
break;
case "dime":
balance=dime.multiply(deposit);
total=total.add(balance);
System.out.println("Your balance is "+ total +" :Make addiontal deposit(s)");
break;
case "nickel":
balance=nickel.multiply(deposit);
total=total.add(balance);
System.out.println("Your balance is "+ total +" :Make addiontal deposit(s)");
break;
case "penny":
balance=penny.multiply(deposit);
total=total.add(balance);
System.out.println("Your balance is "+ total +" :Make addiontal deposit(s)");
break;
case"done":
System.out.println("Your total is $"+total);
fee=total.multiply(feeRate);
System.out.println("The exchance fee is 9.1% which amounts to $"+fee);
grandTotal=total.subtract(fee);
System.out.println("Your total balance minus the exchange fee is $"+grandTotal);
break;
default: System.out.println("There is a issue at "+change);}
} System.out.println("4");
}
}
The key is to change the loop variable so that it becomes false and will thus have you exit the while loop. So change the loop variable in the case "done" block. In that block, set loop = false;
case"done":
System.out.println("Your total is $"+total);
fee=total.multiply(feeRate);
System.out.println("The exchance fee is 9.1% which amounts to $"+fee);
grandTotal=total.subtract(fee);
System.out.println("Your total balance minus the exchange fee is $"+grandTotal);
loop = false; // ************ add this ************
break;
Keep in mind that the key concept is that the thing that is causing the loop to continue must be changed somehow within the loop itself. Otherwise the while loop will never end.
Three methods to break a loop.
A) set your flag variable to false:
loop = false;
Since you already have this variable, this is the much nicer (and simpler) approach.
B) use a labeled break.
label: while(true) {
// ...
switch(something) {
break label; // Without a label, it would only leave the switch!
}
}
Some people will frown upon this last solution, because it is essentially a "goto".
C) use more modular code.
In many cases, the much cleaner way is to use methods. Then you can have "break" to exit an inner loop or switch and return to actually leave the subprocedure and return a result.
This leads to easier-to-understand code, and the semantics of a return are often much more appropriate than those of a break.
Your loop will continue to go round until the loop variable is set to false. In the "done" case, just set that to false. That way, it won't loop back around again.
case"done":
System.out.println("Your total is $"+total);
fee=total.multiply(feeRate);
System.out.println("The exchance fee is 9.1% which amounts to $"+fee);
grandTotal=total.subtract(fee);
System.out.println("Your total balance minus the exchange fee is $"+grandTotal);
loop = false; // This is the line to add.
break;
You have to change the value of the variable loop inside oft the while loop to false.
I guess this should be in the case when the user types done. So in this case add the following line:
loop = false;
anywhere in the case "done": block

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{
}
}
}

Categories

Resources