While-loop equals to not working properly (java bank account) - java

So my task is to write a bank-account program that asks wether you want to deposit or withdraw money, it asks for how much and at last if I want to continue or not, and if not it will show my current account balance. Example:
Deposit or withdraw (0-deposit, 1-withdraw):
How much?
Do you want to continue?
Balance: XX.XX
The program should be looped and break when the answer is "Y" on "Do you want to quit?".
package Account;
import java.util.Scanner;
public class bankVisit {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
bankAccount account = new bankAccount();
String respond = "N";
System.out.print("Deposit or withdraw (0-deposit, 1-withdraw): ");
int choice = scan.nextInt();
while (respond.equals("N")) {
if (choice == 0) {
System.out.print("Amount: ");
double total = scan.nextDouble();
account.credit(total);
System.out.print("Do you want to quit? ");
respond = scan.next();
} else if (choice == 1) {
System.out.print("Amount: ");
double total = scan.nextDouble();
account.withdraw(total);
System.out.print("Do you want to quit? ");
respond = scan.next();
}
System.out.print("Deposit or withdraw (0-deposit, 1-withdraw): ");
choice = scan.nextInt();
}
System.out.println("Balance: " + account.getBalance());
scan.close();
}
}
I get it to loop, but I dont get how I should make the loop to quit, and post my balance, it keeps looping even though "respond" not equals "N".. Any ideas? Im very new to Java so anything will do.

Related

Ending while loop with string not working

I have a problem with trying to end this while loop. When it runs, typing "exit" for the name part doesn't seem to register and the code continues as if "exit" was a name typed in. What I intended to happen is for "exit" to be typed in so that the loop can end. Any help? Here is the code for the class:
import java.util.*;
import java.io.*;
public class BankTest {
public static void main(String args[]) {
List<BankAccount> bank = new ArrayList<BankAccount>();
Scanner scan = new Scanner(System.in);
//enter into list the accounts and end with exit typed in
String name = "";
while (name.contains("exit")==false) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}
//find highest account amount
double largestMon = bank.get(0).getBalance();
String largestPer = bank.get(0).getName();
for (int i=0;i<bank.size();i++) {
double compare = bank.get(i).getBalance();
if (compare>largestMon) {
largestMon = compare;
largestPer = bank.get(i).getName();
}
}
System.out.println(largestPer+" has the largest account with $");
}
}
I've already tried switching between != and equals() compare the strings.
Change while (name.contains("exit")==false) to while(true)
and add line if (name.equals('exit')) break; after name = scan.nextLine();
First of all you could change
name.contains("exit")==falseinto !name.contains("exit")
A better solution would be to use a while true loop and break if the name variable is equal to "exit"
while (true) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
Notice that in cases like this you shouldn't use .contains() or .equals but rather .equalsIgnoreCase()
This should work
while(true){
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}
Modify your while loop as follows:
while (true) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}

How to handle invalid input in java

I am making a simple Bank Deposit and Withdraw code. Code works for Deposit section but at the time of withdraw it asks withdraw values 2 times. And it takes last value for withdraw amount.
I think there I need to enter scannerObject.nextLine(); somewhere, but where and how to use scannerObject.nextLine();?
Following is my sample code. There is one other class file BankAccount.java with only getter and setter methods.
package com.amit;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
boolean option = true;
Scanner scanner = new Scanner(System.in);
while (option){
System.out.println("Press 1 For Deposite. Press 2 For Withdrawal. Press 3 For Exit");
boolean hasvalue = scanner.hasNextInt();
if(hasvalue){
//means user has entered integer value now check if its in 1, 2 if its other
// than this we'll take him out of program to print balance
int userValEntered = scanner.nextInt();
if (userValEntered == 1){
//code for deposite
System.out.println("Enter Amount To Deposite");
Scanner amountToDeposite = new Scanner(System.in);
account.setBalance(amountToDeposite.nextDouble());
}else if (userValEntered == 2) {
//Code for withdrawal
System.out.println("Enter Amount To Withdraw");
Scanner amountToWithdraw = new Scanner(System.in);
if (amountToWithdraw.nextDouble() >= account.getBalance()){
System.out.println("Unable to Withdraw Given Amount, Try Other Amount");
continue;
}else {
double currentBalance = account.getBalance() - amountToWithdraw.nextDouble();
account.setBalance(currentBalance);
System.out.println("Thanks for Doing Business With us");
}
}else{
//if user enters anything other than 1 or 2
break;
}
}else {
//if user enters anything other than integer
break;
}
}
//code to print balance here.
System.out.println("Your Balance is: "+account.getBalance());
}
}
thanks #Tiij7, I found my bug that I was using .nextDouble twice. Now from now on, I'll make sure to save it in variable first, before using it.
This is how I updated my code.
package com.amit;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
boolean option = true;
Scanner scanner = new Scanner(System.in);
while (option){
System.out.println("Press 1 For Deposite. Press 2 For Withdrawal. Press 3 For Exit");
boolean hasvalue = scanner.hasNextInt();
if(hasvalue){
//means user has entered integer value now check if its in 1, 2 if its other
// than this we'll take him out of program to print balance
int userValEntered = scanner.nextInt();
if (userValEntered == 1){
//code for deposite
System.out.println("Enter Amount To Deposite");
Scanner amountToDeposite = new Scanner(System.in);
account.setBalance(amountToDeposite.nextDouble());
}else if (userValEntered == 2) {
//Code for withdrawal
System.out.println("Enter Amount To Withdraw");
Scanner amountToWithdraw = new Scanner(System.in);
double withdrawAmt = amountToWithdraw.nextDouble();
if (withdrawAmt >= account.getBalance()){
System.out.println("Unable to Withdraw Given Amount, Try Other Amount");
continue;
}else {
double currentBalance = account.getBalance() - withdrawAmt;
account.setBalance(currentBalance);
System.out.println("Thanks for Doing Business With us");
}
}else{
//if user enters anything other than 1 or 2
break;
}
}else {
//if user enters anything other than integer
break;
}
}
//code to print balance here.
System.out.println("Your Balance is: "+account.getBalance());
}
}

Java - Do you want to continue?(Y/N)

I want to write a simple loop for the program to go back and restart it again.
Just a simple 1 question program. Then the system ask if the user want to do it again. If the user inputs Y ... the program will loop it back to the beginning and run the entire program again. If the user inputs N, it exits.
import java.util.Scanner; // show them as code
public class HowToDoLoop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
while(true){
System.out.println("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
String c = input.nextLine();
if(c.equalsIgnoreCase("n")){
break;
}//else continue to loop on any string ;-)
}
String c = "";
do{
System.out.println("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
c = input.nextLine();
}while(c.equalsIgnoreCase("Y"));

Exception Thread in Do-While Loop

I'm working on a project that calculates the value of a bank account based on starting balance(b), interest rate(IR), and quarters to display. My entire code works perfectly, but the very last portion is to make sure the variables like interest rate are within the confines of the boundaries my professor gave me. I do need to display an error message if the user enters a value outside the boundaries and ask for the value again.
For example, the number of quarters to display needs to be greater than zero, and less or equal to 10.
As you can see, pretty much all of my program is in a do-while loop. I know I can have nested loops, but what would I be able to put in my do-while loop that would work in this situation? An if-else statement? Try and catch block? Another while loop?
If I used a try-catch, then could anyone give me an example of how I could do that? Thank you very much for your time, and all help is appreciated! The below is my code for reference.
import java.util.Scanner;
public class InterestCalculator
{
public static void main(String[] args)
{
Scanner scannerObject = new Scanner(System.in);
Scanner input = new Scanner(System.in);
int quartersDisplayed;
double b, IR;
do
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
quartersDisplayed = keyboard.nextInt();
System.out.println("Next enter the starting balance. ");
System.out.println("This input must be greater than zero: ");
b = keyboard.nextDouble();
System.out.println("Finally, enter the interest rate ");
System.out.println("which must be greater than zero and less than or equal to twenty percent: ");
IR = keyboard.nextDouble();
System.out.println("You have entered the following amount of quarters: " + quartersDisplayed);
System.out.println("You also entered the starting balance of: " + b);
System.out.println("Finally, you entered the following of interest rate: " + IR);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = b + (b * IR/100 * .25);
System.out.println("Your ending balance for your quarters is " + quarterlyEndingBalance);
System.out.println("Do you want to continue?");
String yes=keyboard.next("yes");
if (yes.equals(yes))
continue;
else
break;
}
while(true);
}
}
So here's some code to answer your questions and help get you started. However, there are problems with your logic that do not pertain to your question which I will address afterward.
Note: I have added comments to your code. Most of them start with "EDIT:" so that you can tell what I changed. I didn't use this prefix in all cases because some of it is new code and it's obviously my comment
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
// EDIT: you already have a scanner defined below with a more meaningful name so I removed this one
// Scanner scannerObject = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//EDIT: defining userResponse outside the loop so we can use it everywhere inside
String userResponse = null;
do {
//EDIT: moved the variables inside the loop so that they are reset each time we start over.
//EDIT: initialize your variable to a value that is invalid so that you can tell if it has been set or not.
int quartersDisplayed = -1;
//EDIT: gave your variables more meaningful names that conform to java standards
double startingBalance = -1, interestRate = -1;
//EDIT: you don't need a second Scanner, just use the one you already have.
// Scanner keyboard = new Scanner(System.in);
do{
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
do{
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try{
startingBalance = Double.parseDouble(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
if(startingBalance <= 0){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
do{
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try{
interestRate = Double.parseDouble(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
//Note: I assume twenty percent is represented as 20.0 here
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
System.out.println("You have entered the following amount of quarters: "
+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "
+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "
+ quarterlyEndingBalance);
System.out.println("Do you want to continue?");
//EDIT: modified your variable name to be more meaningful since the user's response doesn't have to "yes" necessarily
userResponse = input.next();
// EDIT: modified the logic here to compare with "yes" or "y" case insensitively.
// if (userResponse.equals(userResponse))
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
} while (true);
Now to address other issues - your interest calculation doesn't seem correct to me. Your formula does not make use of the quartersDisplayed variable at all. I assume you're compounding the interest quarterly so you will definitely need to make use of this when calculating your results.
This may be beyond the scope of your project, but you should not use double or float data types to represent money. There is a stackoverflow question about this topic that has good information.
Possible improvements - since you're asking the user for two values of type double you could create a method to ask for a double value and call it twice instead of repeating the code. This is a better approach because it helps reduce the chance of mistakes and makes testing and maintenance easier.
You can do something like this in your do/while loop:
do
{
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
quartersDisplayed = keyboard.nextInt();
}
while (quartersDisplayed < 1 || quartersDisplayed > 10);
System.out.println("Next enter the starting balance. ");
do
{
System.out.println("This input must be greater than zero: ");
b = keyboard.nextDouble();
}
while (b < 1);
// rest of code ...
}
With the Scanner#hasNextInt (and the equivalent for double), you can avoid having exceptions thrown, and thus don't need try-catch clauses. I think in general if you can avoid try-catch, it's good, because they are clumsy - but I might be wrong.
However, my approach is like this. Inside your outer do-while, have three other do-while-loops to get the three values. The reason is that you want to keep looping until you get a correct value. The explanation of why keyboard.nextLine() is important is covered here.
I didn't include all of your code, only the part in question. Here's my take on it:
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int quartersDisplayed = -1;
double b = -1.0;
double IR = -1.0;
do {
do {
System.out.println("Enter the number of quarters.");
if(keyboard.hasNextInt()) {
quartersDisplayed = keyboard.nextInt();
keyboard.nextLine(); //important
} else {
System.out.println("You need to enter an integer.");
continue;
}
} while(quartersDisplayed < 1 || quartersDisplayed > 10);
do {
System.out.println("Enter the starting balance.");
if(keyboard.hasNextDouble()) {
b = keyboard.nextDouble();
keyboard.nextLine();
} else {
System.out.println("You must enter a number.");
continue;
}
} while(b <= 0);
do {
System.out.println("Enter the interest rate.");
if(keyboard.hasNextDouble()) {
IR = keyboard.nextDouble();
keyboard.nextLine();
} else {
System.out.println("You must enter a number.");
continue;
}
} while(IR <= 0 || IR > 20.0);
//... rest of code
} while(true);
}
}

Tip Calculator statement confusion

Here is the code. Basically after I enter the second customers bill amount it will prematurely read me a tip and asks if there is another customer. I want it to ask me if there is another customer but I don't want it to ask about the tip till I enter "n". Any thoughts?
import java.util.Scanner;
public class H3_TipCalc {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Please enter your bill amount.");
double bill = input.nextDouble();
String multiplecust = ("Y");
//int mc=1;
while (multiplecust.equalsIgnoreCase("y"))
{
Scanner usrin = new Scanner (System.in);
System.out.println("Is there another customer? y or n?");
multiplecust = usrin.nextLine();
//mc++;
if (multiplecust.equals("y")){
System.out.println("Please enter their bill amount.");
}
else if (multiplecust.equals("n")){
System.out.println("What tip prcentage would you like to use? Enter as a decimal.");
}
double tip = usrin.nextDouble();
System.out.println("Your tip owed will be " + bill*tip + ".");
}
}
}
Because of the else if, you can either enter the last customer's bill amount or the tip percentage, but not both. Instead, try this logic:
while( there are more individual customer amounts to enter ) {
enter next customer amount
}
get tip percentage
show final bill
Notice that the tip percentage is entered after the while loop, because it's just a one-time entry.
You got your logic twisted.
Better move the complete logic inside the loop and check for exit at the end of it (not the start):
do
read bill amount
read tip amount
read next customer
while (wants to continue)

Categories

Resources