Hi below is my Progarm
import java.util.Scanner;
public class Usecase1 {
public static void main(String[] args) {
Usecase1 us = new Usecase1();
us.withdrawl();
}
public void withdrawl() {
System.out.println("your Account number is....0091236452312");
System.out.println("please enter your pin number(1234)....");
Scanner sc = new Scanner(System.in);
int pinno = sc.nextInt();
if (pinno == 1234) {
System.out
.println("Please select type of Transaction 1.Balance Enquiry 2.Withdraw Money");
int option = sc.nextInt();
System.out.println("your choice is..." + option);
int totalamount = 85000;
if (option == 2) {
System.out.println("enter amount to withdraw");
int amount = sc.nextInt();
System.out.println("Remaining Balance in your account is..."
+ (totalamount - amount));
}
}
}
}
My requirement is to user can give his choice as 2 any number of times, for every time the below loop should be repeated please help me how to do this.
(option == 2) {
System.out.println("enter amount to withdraw");
int amount = sc.nextInt();
System.out.println("Remaining Balance in your account is..."
+ (totalamount - amount));
}
use while loop for that and a boolean to flag the loop
boolean isValid = true;
int totalamount = 85000;
while(isValid){
System.out.println("Please select type of Transaction 1.Balance Enquiry 2.Withdraw Money 3.Exit");
int option = sc.nextInt();
System.out.println("your choice is..." + option);
if (option == 2) {
System.out.println("enter amount to withdraw");
int amount = sc.nextInt();
System.out.println("Remaining Balance in your account is..."
+ (totalamount - amount));
} else if(option == 3){
//exit
isValid = false;
}
System.out.println("Do you want to continue? 1.yes 2.no");
int lastPrompt = sc.nextInt();
if(lastPrompt == 2){
break; or isValid = false;
}
}
use a while loop and
use break or continue to control over loop based on you condition.
eg-
while(true){
if (option == 2) {
System.out.println("enter amount to withdraw");
int amount = sc.nextInt();
System.out.println("Remaining Balance in your account is..."
+ (totalamount - amount));
}
else{
break;//break the loop
//or you may continue the loop
}
}
Replace the if(option == 2) with a while loop:
while (option == 2) {
System.out.println("enter amount to withdraw");
int amount = sc.nextInt();
System.out.println("Remaining Balance in your account is..." + (totalamount - amount));
//Stay in the loop if option is 2 again
option = sc.nextInt();
}
But if you want to consider more options, then use a flag like in the answers below
Related
My question is in relation to my line of code resembling an ATM. The current balance being 10000, What i have written shows a message to the user that if they withdraw over the given balance that it is Insufficient balance. However the balance continues to change thus when Inquiring balance the balance is now < the allowed balance. My question is how should i go about resetting the double value for the balance when the Insufficient balance message is shown to the user?
Here is my code.
import java.util.Scanner;
class app {
public static void main(String[] args)
{
long pin = 2927942074l;
double balance = 10000.0;
int attempts = 3;
System.out.println("Please enter your pin.");
while (attempts > 0) {
Scanner keyboardpin = new Scanner(System.in);
long input = keyboardpin.nextLong();
if (input == pin) {
System.out.println("Correct");
System.out.println("Welcome to your ATM");
while (true) { // Keep printing your options unless "Quit" is chosen
int a = 1;
int b = 2;
int c = 3;
int d = 0;
System.out.println(a + " - Inquire Balance");
System.out.println(b + " - Withdraw");
System.out.println(c + " - Deposit");
System.out.println(d + " - Quit");
System.out.println("Please select what you want to do.");
Scanner menuselect = new Scanner(System.in);
int menuinput = menuselect.nextInt();
if (menuinput == a) {
System.out.println(balance);
continue;
}
if (menuinput == b) {
System.out.println("Please enter a withdrawal amount.");
Scanner withdrawamount = new Scanner(System.in);
double withdrawbalace = withdrawamount.nextDouble();
balance = (balance - withdrawbalace);
if (withdrawbalace > balance)
System.out.println("Insufficient balance");
if (withdrawbalace <= balance)
System.out.println("Youre new balance is " + balance);
}
if (menuinput == c) {
}
if (menuinput == d) {
break;
}
if (attempts == 0) {
System.out.println("Maximum number of attempts exceeded");
}
}
} else {
System.out.println("Wrong");
attempts--;
System.out.println("You have " + attempts + " attempts remaining.");
}
}
}
}
Just check whether the user has enough balance before subtracting the amount.
if (menuinput == b) {
System.out.println("Please enter a withdrawal amount.");
Scanner withdrawamount = new Scanner(System.in);
double withdrawbalace = withdrawamount.nextDouble();
if (withdrawbalace > balance)
System.out.println("Insufficient balance");
if (withdrawbalace <= balance)
balance = (balance - withdrawbalace);
System.out.println("Youre new balance is " + balance);
}
Your main problem has been solved in the previous answer, but your code logic has some errors. I have fixed it for you.
import java.util.Scanner;
class app {
public static void main(String[] args) {
final long pin = 2927942074L;
double balance = 10000.0;
int attempts = 3;
System.out.println("Please enter your pin.");
Scanner keyboard = new Scanner(System.in);
while (attempts > 0) {
long input = keyboard.nextLong();
if (input == pin) {
System.out.println("Correct");
System.out.println("Welcome to your ATM");
// Keep printing your options unless "Quit" is chosen
while (true) {
int a = 1;
int b = 2;
int c = 3;
int d = 0;
System.out.println(a + " - Inquire Balance");
System.out.println(b + " - Withdraw");
System.out.println(c + " - Deposit");
System.out.println(d + " - Quit");
System.out.println("Please select what you want to do.");
int menuInput = keyboard.nextInt();
if (menuInput == a) {
System.out.println(balance);
} else if (menuInput == b) {
System.out.println("Please enter a withdrawal amount.");
double withdrawBalance = keyboard.nextDouble();
if (balance >= withdrawBalance) {
balance -= withdrawBalance;
System.out.println("Your new balance is " + balance);
} else System.out.println("Insufficient balance");
} else if (menuInput == c) {
// Deposit code here
} else if (menuInput == d) break;
}
} else {
attempts--;
if (attempts == 0) {
System.out.println("Maximum number of attempts exceeded");
break;
}
System.out.println("Wrong");
System.out.println("You have " + attempts + " attempts remaining.");
}
}
keyboard.close();
}
}
And here are some tips...
Try to choose meaningful variable names.
If the variable has a constant value make it final
If the variable name consists of two, or more, words capitalize the first letter of the second word (eg. menuInput)
If you check the same condition for different cases you can use switch or if, else if, else
Never forget to close the objects you used to release memory
Good Luck
I am currently making a simple ATM program in java.
I want to write a while loop where when user enters wrong pin it will prompt the user to enter again until the pin is matched. When the pin is matched, it will display the main menu.
I tried by myself, but I don't know how to fix it.
while(userPIN != savedPIN)
{
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
int pass = again.nextInt();
break;
}
Remove the `break;' statement and update userPIN with the new pin as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int savedPIN = 4444;
Scanner input = new Scanner(System.in);
System.out.println("Enter password");
int userPIN = input.nextInt();
double withdraw = 0.0, amount = 0.0, deposit = 0.0;
while (userPIN != savedPIN) {
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
userPIN = again.nextInt();
}
while (userPIN == savedPIN) {
System.out.println(" 1 - Inquire Balance \n 2 - Withdraw \n 3 - Deposit \n 0 - Quit ");
Scanner inputNum = new Scanner(System.in);
int number = inputNum.nextInt();
switch (number) {
case 1:
System.out.println("The current balance is $" + amount);
break;
case 2:
System.out.println("Enter the amount to withdraw : ");
withdraw = input.nextDouble();
if (amount >= withdraw) {
amount = amount - withdraw;
System.out.println("The current balance is $" + amount);
} else {
System.out.println("Insufficient balance");
}
break;
case 3:
System.out.println("Enter the amount to deposit : ");
deposit = input.nextDouble();
amount = amount + deposit;
System.out.println("The current balance is $" + amount);
break;
case 0:
System.exit(4);
}
}
}
}
Ok 2 errors:
1)you test userPIN != savedPIN but you accept the value into variable pass with which you do nothing.
2)remove the break in the first loop it will always exit without looping.
it should look like :
while(pass!= savedPIN)
{
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
int pass = again.nextInt();
}
I am working on a Java project and am encountering a strange error. I have a menu with multiple options all inside a do while loop but I want the variable pizzasOrdered to keep increasing when the user adds more pizzas to his order. Here is my code:
import java.util.Scanner;
public class PizzaMenu {
public static void main(String[] args) {
int numPlain;
int numPepperoni;
int pizzasOrdered = 0;
boolean flag = true;
System.out.println("Welcome to Pies, Pies, and pis!");
Scanner kbd = new Scanner(System.in);
System.out.println("Is there a customer in line? (1 = yes, 2 = no)");
int isCustomer = kbd.nextInt();
System.out.println("Are you a Pie Card member? (1 = yes, 2 = no)");
boolean isMember;
int pieCardResponse = kbd.nextInt();
if(pieCardResponse == 1)
{
isMember = true;
}
else
{
isMember = false;
}
do{
System.out.println("Please choose an option: \n\t1) Update Pizza Order\n\t2) Update Cherry Pie Order\n\t3) Update Charm Order\n\t4) Check Out");
int option = kbd.nextInt();
if(option == 1)
{
System.out.println("Here is your current order: \n\t" + pizzasOrdered + " pizzas ordered");
System.out.println("How many plain pizzas would you like for $10.00 each?");
numPlain = kbd.nextInt();
System.out.println("How many pepperoni pizzas would you like for $12.00 each?");
numPepperoni = kbd.nextInt();
pizzasOrdered = numPlain + numPepperoni;
}
else if(option == 2)
{
System.out.println("Here is your current order: \n");
}
else if(option == 3)
{
}
else if(option == 4)
{
}
}while(flag);
}
}
You should change this
pizzasOrdered = numPlain + numPepperoni;
to
pizzasOrdered += (numPlain + numPepperoni);
In your case you are not incrementing the variable, you are just assigning it new values in every iteration.
I'm not very adept in getting the running totals using Java as I've started recently. I have to display and hold the running total of the bank balance and for some strange reason, it's resetting back to 100, which is what I declared it as to start with. Is there any way for me to stop the bank balance from being reset every time it loops?
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int choice, totBal = 0, totWith = 0, totDep = 0;
double with, remBal = 0, deposit, bankBal = 100;
char reply = 0;
do
{
System.out.println("");
System.out.println("Bank online\n");
System.out.println("1. Withdraw");
System.out.println("2. Deposit");
System.out.println("3. Balance");
System.out.println("4. Account Details");
System.out.println("5. Exit\n");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
if(choice == 1)
{
System.out.print("How much do you wish to withdraw?\n");
with = sc.nextInt();
remBal = bankBal - with;
System.out.println("Your new balance is: " + remBal);
totWith++;
}
else if(choice == 2)
{
System.out.print("How much do you wish to deposit?\n");
deposit = sc.nextInt();
remBal = remBal + deposit;
System.out.println("Your new balance is: " + remBal);
totDep++;
}
else if(choice == 3)
{
System.out.println("Your balance is: " + remBal);
totBal++;
}
else if(choice == 4)
{
System.out.println("You made " + totWith + " withdrawls from your account.");
System.out.println("You made " + totDep + " deposits to your account.");
System.out.println("You made " + totBal + " balance checks on your account.");
}
else if(choice == 5)
{
}
System.out.println("");
System.out.print("Do you want to enter another option?(y/n): ");
reply = sc.next().charAt(0);
}while(reply == 'Y' || reply == 'y');
System.out.println("Thank you and goodbye!");
}
}
Also, I feel that I have WAY too many variables. How can I cut back on these?
Your problem is with following statement:
double with, remBal = 0, deposit, bankBal = 100;
Here you are initialising remBal as 0, while when one deposits amount/checks balance you do:
remBal = remBal + deposit;//you use remBal for blaance check
So on first attempt it will try to add 0 with say $100 which will be 100 while bankBal is 100 it should be 100. So initialize remBal same as bankBal (or use just one variable for bankBalance i.e. either of one).
You set the bankBal value to 100 at the start of the program.
When doing withdrawals, you always do
remBal = bankBal - with
which will always equate to
remBal = 100 - with
since you never change bankBal to reflect the updated balance after each loop.
One approach to solve this is to remove the
bankBal
variable altogether and simply set your
remBal
variable to your desired starting value.
Finally change the withdrawal computation mentioned above to
remBal = remBal - with
One thing you can do is implement switch-cases to call methods specific to Depost, Withdraw, etc. An example of this roughly would be:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please Enter what you would like to do: ");
String enterPrompt = input.next();
int options = 5;
switch (options) {
case 1: enterPrompt = "Deposit";
doDeposit();
break;
case 2: enterPrompt = "Withdrawel";
doWithdrawel();
break;
case 3: enterPrompt = "Balance";
viewBalance();
break;
case 4: enterPrompt = "Account Details";
viewAccount();
break;
case 5: enterPrompt = "Exit";
System.exit(1);
break;
}
public void doDeposit(){
//local variables here
//Do stuff
}
public void doWithdrawel(){
//local variables here
//Do stuff
}
public void viewBalance(){
//local variables here
//Do stuff
}
public void viewAccount(){
//local variables here
//Do stuff
}
}
sorry for asking such an in depth question, but I'm very lost. I am working on a problem and I am stuck. I am supposed to make a basic menu driven calculator that add, subtract, multiply, divide, or generate a random number between an upper and lower limit. I made that without too much difficulty, but now I need to change it so that after it performs an operation it starts over again and displays the menu. Also, if I enter an invalid response, it needs to let them try again until they enter a valid one UNLESS they enter an invalid response THREE TIMES IN A ROW; then it needs to display a message about trying again later and exiting the program. This is there I am stuck. I have tried every combination of for and while in the following code but i can not get this to work. I would really appreciate any pointers.
Here are the requirements:
The menu is repeatedly displayed until a valid option is entered
If the user enters three invalid choices in a row, the program ends
If the user enters two invalid choices, then a valid one, then another invalid one, the program does NOT end
The program computes the correct answers for each menu option
The program continues after a valid operation by re-displaying the menu
The program ends when the user chooses the Quit option from the menu
• The program does not end on division by zero – just display an error message and allow the user to retry
And here is what i have thus far.
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double numONE = 0.0;
double numTWO = 0.0;
double upperLimit = 0.0;
double lowerLimit = 0.0;
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
int menuSelect = input.nextInt();
//Selects an item from the menu
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
System.out.println("Enter first number.");
numONE = input.nextDouble();
//Stores input as numONE
System.out.println("Enter second number.");
numTWO = input.nextDouble();
//Stores input as numTWO
}
if(menuSelect == 1){
System.out.println(numONE + numTWO);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(numONE - numTWO);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(numONE * numTWO);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(numTWO != 0){
System.out.println(numONE / numTWO);
//Divides first number by second number
}
else if(numTWO == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
System.out.println("Enter upper limit.");
upperLimit = input.nextDouble();
System.out.println("Enter lower limit.");
lowerLimit = input.nextDouble();
double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
}
else if(menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
}
else{
System.out.println("Sorry, "+menuSelect+" is not an option.");
}
}
}
Look at lines I added ( // <- new code )
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
int counter_WrongAttempts = 0; // <- new code
boolean flag_Quit = false; // <- new code
while (!flag_Quit) { // <- new code
boolean wrongAttempt = false; // <- new code
Scanner input = new Scanner(System.in);
double numONE = 0.0;
double numTWO = 0.0;
double upperLimit = 0.0;
double lowerLimit = 0.0;
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
int menuSelect = input.nextInt();
//Selects an item from the menu
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
System.out.println("Enter first number.");
numONE = input.nextDouble();
//Stores input as numONE
System.out.println("Enter second number.");
numTWO = input.nextDouble();
//Stores input as numTWO
}
if(menuSelect == 1){
System.out.println(numONE + numTWO);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(numONE - numTWO);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(numONE * numTWO);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(numTWO != 0){
System.out.println(numONE / numTWO);
//Divides first number by second number
}
else if(numTWO == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
System.out.println("Enter upper limit.");
upperLimit = input.nextDouble();
System.out.println("Enter lower limit.");
lowerLimit = input.nextDouble();
double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
}
else if(menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
flag_Quit = true; // <- new code
}
else{
System.out.println("Sorry, "+menuSelect+" is not an option.");
wrongAttempt = true; // <- new code
}
if (wrongAttempt) // <- new code
counter_WrongAttempts++; // <- new code
else // <- new code
counter_WrongAttempts = 0; // <- new code
flag_Quit = flag_Quit || (counter_WrongAttempts >= 3); // <- new code
}
}
}
This isn't about a 'for loop inside a while loop', you don't even need it.
Imagine the following pseudo-code:
int invalidOptions = 0;
while ( invalidOptions < 3 ) {
// show menu
displayMenu();
// read option
int input = readInput();
// validate input
if ( isInputValid(input) ) {
// check whether the user wants to exit or not
if (input == EXIT_INPUT) {
break;
}
// handle other commands
handleInput(input);
} else {
// input is invalid
invalidOptions++;
}
}
That's all you need, it's better to split your program into smaller pieces, it will be easier to maintain and understand.
First things first, you don't really need four variables for this program. Since you are always taking two numbers as input you can easily store them in two variables, instead of having different variable names for each case.
As mentioned above, you don't need such complex loop nesting. A simple while that checks the number of errors is less than 3 will do just fine. Also, you seem to work well with the System.out.println() command, but for some applications, like input, it may be better to work with System.out.print(), it's basically the same but does not start a new line. Try the code below to see the results.
Another thing you might consider is using a switch sentence instead of the if, else if, else if statements.
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double firstNumber = 0.0;
double secondNumber = 0.0;
//New variable
int errors = 0;
while (errors < 3) {
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
System.out.print("> ");
int menuSelect = input.nextInt();
//Selects an item from the menu
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4) {
errors = 0;
System.out.print("Enter first number: ");
firstNumber = input.nextDouble();
//Stores input as the firstNumber
System.out.print("Enter second number: ");
secondNumber = input.nextDouble();
//Stores input as the secondNumber
}
if(menuSelect == 1){
System.out.println(firstNumber + secondNumber);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(firstNumber - secondNumber);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(firstNumber * secondNumber);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(secondNumber != 0){
System.out.println(firstNumber / secondNumber);
//Divides first number by second number
}
else if(secondNumber == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
errors = 0;
System.out.print("Enter upper limit: ");
firstNumber = input.nextDouble();
System.out.print("Enter lower limit: ");
secondNumber = input.nextDouble();
double randomVal = (firstNumber + (int)(Math.random() * ((firstNumber - secondNumber)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
}
else if (menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
}
else{
errors++;
System.out.println("Sorry, "+ menuSelect + " is not an option.");
}
}
input.close();
System.out.println("Program will exit now");
}
}
int unvalid = 0;
while (unvalid < 3)
{
//read stuff
if ([stuff is valid])
{
unvalid = 0;
}
else
{
unvalid++;
}
}
You probably don't want a for loop inside a while loop to handle this. I would just have a variable to track how many invalid inputs you've received, increment it when they enter something invalid, reset it to zero if they enter something valid, and kick them out if it gets too high.
eg:
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double numONE = 0.0;
double numTWO = 0.0;
double upperLimit = 0.0;
double lowerLimit = 0.0;
int invalid = 0;
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
int menuSelect = input.nextInt();
//Selects an item from the menu
while(invalid < 3){
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
System.out.println("Enter first number.");
numONE = input.nextDouble();
//Stores input as numONE
System.out.println("Enter second number.");
numTWO = input.nextDouble();
//Stores input as numTWO
invalid = 0;
}
if(menuSelect == 1){
System.out.println(numONE + numTWO);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(numONE - numTWO);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(numONE * numTWO);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(numTWO != 0){
System.out.println(numONE / numTWO);
//Divides first number by second number
}
else if(numTWO == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
System.out.println("Enter upper limit.");
upperLimit = input.nextDouble();
System.out.println("Enter lower limit.");
lowerLimit = input.nextDouble();
double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
invalid = 0;
}
else if(menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
}
else{
System.out.println("Sorry, "+menuSelect+" is not an option.");
invalid++;
}
}
System.out.println("Too many invalid inputs. Try again later");
}
}