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
}
}
Related
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();
}
this project i use do while loop with switch case to check the input case is not match or not. i run the code but the result not what i wanted. what i expect is if the user type the wrong case, the do while loop will loop back to the input where user need to enter the case.
here is the code
package vending.machine;
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
import static vending.machine.adddrinks.drinksList;
public class VendingMachine {
public static void main (String []args){
Scanner sc= new Scanner(System.in);
double money;
double total;
double balance;
do{
System.out.println("\nPlease insert money:");
money = sc.nextDouble();
if(money < 1.2){
System.out.println("Not enough money");
}
}while(money < 1.2);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
System.out.print("Select: 1 or 2 or 3 or 4\n");
int select=sc.nextInt();
do{
switch(select){
case 1:{
total = adddrinks.drinksList.get(0).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 2:{
total = adddrinks.drinksList.get(1).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 3:{
total = adddrinks.drinksList.get(2).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 4:{
total = adddrinks.drinksList.get(3).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
default:{
System.out.println("Invalid");
break;
}
}
}while(select<5);
}
}
here is the result
enter image description here
From what I understood from your code. When you are giving the input as 5 it is giving invalid.
After that it will go to the while statement and check the condition there. If you are inside the switch case and select any random case It will show you invalid. After that depending upon the number that you have entered.
If the number is less than 5, It will again go to switch case.
As it doesn't make sense as If you continue to provide correct input to it. The code will continue to execute making the balance going in the negative. this condition should be changed to
while(balance>1.2)
assuming that it is minimum amount that is necessary to buy a drink. This will check the condition after every drink and will hopefully do what you were hoping.
On side Note : Make your code modular.
You need to loop over your input, i was so free to improve your code a bit (sorry I do not like repetations):
private static void main10(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
int select = 0;
double balance = 0;
boolean running = true;
while (running) {
if (sc.hasNextInt()) {
select = sc.nextInt();
if (0 < select && select <= adddrinks.drinksList.size()) {
double price = adddrinks.drinksList.get(select - 1).getdrinkPrice();
if (balance < price) {
System.out.println("Not enough money, " + select + " costs " + price);
} else {
balance -= price;
System.out.println("You choosed " + select + " , you will find it in the dispenser");
}
} else {
System.out.println("Invalid input, please retry");
}
} else if (sc.hasNextDouble()) {
balance += sc.nextDouble();
} else {
String input = sc.next();
if (input == "q") {
running = false;
if (0 < balance)
System.out.println("please don't forget your change with amount of: " + balance);
System.out.println("Have a nice day, happy to see you again");
break;
} else if (input == "h") {
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
} else {
System.out.println("Invalid input, please retry");
}
}
System.out.println("Your balance is: " + balance);
System.out.println(
"please chouce your product (e.g 2), enter coins (e.g 2.0), click on 'h' to show product list or click on 'q' to get your change");
}
}
import java.util.*;
public class TestProject
{
public static void theMath()
{
double add = 1;
double subtract = 2;
double multiply = 3;
double divide = 4;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Pick first number
System.out.println("Please enter a number: ");
int intOne = input.nextInt();
// Pick second number
System.out.println("Please enter another number: ");
int intTwo = input.nextInt();
//User chooses operator
System.out.println("Now please choose an operator (1 for add, 2 for subtract, 3 for mulitply, 4 for divide): ");
int userChoice = input.nextInt();
// Add
if (userChoice == add)
System.out.println("Your answer is: " + (intOne + intTwo));
// Subtract
else if (userChoice == subtract)
System.out.println("Your answer is: " + (intOne - intTwo));
// Multiply
else if (userChoice == multiply)
System.out.println("Your answer is: " + (intOne * intTwo));
// Divide
else if (userChoice == divide)
System.out.println("Your answer is: " + (intOne / intTwo));
// If wrong input
else
{
System.out.println("Nothing happens!");
System.out.println("Please make sure you entered a number and an operator.");
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
theMath();
System.out.println("Would you like to do another calculation?");
String redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}
}
I was wondering how I could recall the main method an infinite amount of times if I wanted to. What I was doing was just copying and pasting it over and over again but there has to be a better way. And also, I would like to know how to return a value has a decimal(so I could do 25/6 and get the correct answer).
Why not put only the statements that should be repeated inside a loop?
String redo;
do{
System.out.println("Would you like to do another calculation?");
redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}while(redo.equals("yes"))
As for the other part of your question. If you have two int values and want to get a decimal from a division, you can do it like this:
int x = 2;
int y = 3;
double result = (double)x/y;
System.out.println(result);
This is called casting.
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
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I know these must be basic errors, but I'm not sure how to fix them.
I changed my class name to Interface & now Java has a problem with it.
Also, in my switch statement, I've tried to call the enterData method, but I'm getting an error on this line as well as on this line... "private static void enterData()" <-- it says a "token" is missing on this line?
I'm trying to call a method from case 0, but it isn't working.
import java.util.Scanner;
public class Interface {
private void run()
{
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
do {
System.out.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch(option)
{
case 0: enterData();
break;
case 1:
break;
case 2:
break;
case 9: System.out.println("You chose to exit the program.");
break;
default: System.out.println("Please choose a valid option.");
}
} while (option != 9);
private static void enterData()
{
System.out.println("Product name between 3 & 10 characters long: ");
name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
You can't define method in another method.
Change your code to this:
public class Interface {
private void run()
{
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
do {
System.out.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch(option)
{
case 0: enterData();
break;
case 1:
break;
case 2:
break;
case 9: System.out.println("You chose to exit the program.");
break;
default: System.out.println("Please choose a valid option.");
}
} while (option != 9);
}
private static void enterData()
{
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
Scanner console = new Scanner(System.in);
System.out.println("Product name between 3 & 10 characters long: ");
String name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
Try making a separate method and make those fields global. Something like this
import java.util.Scanner;
public class Interface {
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
private void run() {
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
do {
System.out
.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch (option) {
case 0:
enterData(console);
break;
case 1:
break;
case 2:
break;
case 9:
System.out.println("You chose to exit the program.");
break;
default:
System.out.println("Please choose a valid option.");
}
} while (option != 9);
}
private void enterData(Scanner console) {
System.out.println("Product name between 3 & 10 characters long: ");
name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out
.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
Interface is some kind of an abstract class definition keyword in java.
You can use a keyword to name your class with capitalized letters, but seriously, don't do this.
And you are not calling a method, you are implementing it in another method. You should go over writing and calling a method in java once again ;)