I have to write a ATM program for my computer science class. It works for the most part, apart from a couple logic problems within the programs itself. So far, from what I can tell, my ATM will deposit the correct amount of money that I tell it to however, when I withdraw money, it does not always withdraw the correct amount if I purposefully make an error (such as trying to take out an amount that is not a multiple of 20). I am also running into an issue where if I try to take out more money then is actually in the account, it will become a negative value, which I do not want to be allowed. I want it not to subtract the value that causes it to become negative and for it to prompt the user until a value less then or equivalent to the balance is able to be taken out. I am rather new to coding so please excuse my rather messy code. My error is probably around the else if statement where option == 3. Here is my code:
import java.io.*;
import java.util.*;
public class aTMLauncher
{
public static int options=0;
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
aTMTester atm = new aTMTester();
System.out.println("Login: \n(case sensitive)");
System.out.print("Username > ");
String usernameInput=input.nextLine();
int count=4;
while (!usernameInput.equals(aTMTester.getUsername()))
{
System.out.println("\nIncorrect input. Please try again. You have " + (count-1) + " trys remaining attempts.");
System.out.println("Login: \n(case sensitive)");
System.out.print("Username > ");
count--;
if(count==0)
{
System.out.println("No remain attempts, system will now exit");
System.exit(0);
}
usernameInput = input.nextLine();
}
System.out.print("Pin > ");
int PINInput=input.nextInt();
int count1=4;
while (PINInput<aTMTester.getPIN() || PINInput>aTMTester.getPIN())
{
System.out.println("\nIncorrect input. Please try again. You have " + (count1-1) + " trys remaining");
System.out.print("Pin > ");
count1--;
PINInput=input.nextInt();
if(count1==0)
{
System.out.println("No remain attempts, system will now exit");
System.exit(0);
}
}
System.out.println("\nWelcome, " + aTMTester.getUsername() +"!");
while(PINInput==2468)
{
atm.main();
options = input.nextInt();
if (options==4)
{
atm.logout();
}
else if(options==2)
{
System.out.println("How much money would you like to deposit?");
System.out.print("$ ");
atm.deposit = input.nextInt();
atm.balance+=atm.deposit;
System.out.println("Your new balance is $" + atm.balance +"0");
}
else if(options==3)
{
System.out.println("How much money will you be withdrawing? \n(Only amounts divisible by 20 are accepted) \n$");
atm.withdraw= input.nextInt();
atm.balance-=atm.withdraw;
if(atm.withdraw%20==0.0)
{
System.out.println("You took out " +atm.withdraw);
System.out.println("Your new balance is $" + atm.balance);
}
while(atm.withdraw%20>0)
{
System.out.println("Invalid withdraw amount. Please retry.");
System.out.println("\nHow much money will you be withdrawing? \n(Only amounts divisible by 20 are accepted)");
atm.withdraw= input.nextInt();
System.out.println("You took out " +atm.withdraw);
System.out.println("Your new balance is $" + atm.balance);
}
if(!(atm.balance>0.0))
{
System.out.println("You are not allowed to take out more then you have in your account \n Please retry");
atm.withdraw= input.nextInt();
}
}
else if(options==1)
{
System.out.println("Your account balance is $"+atm.balance+"0");
}
}
}
}
public class aTMTester
{
private static final String username = "David";
private static final int PIN = 2468;
public static int deposit, withdraw;
public static double balance=0.00;
private String menu;
/*
* Default constructor
*/
public aTMTester()
{
}
public static String getUsername()
{
return username;
}
public static int getPIN()
{
return PIN;
}
public static void main()
{
System.out.println("\n+++++++++++Account: "+ username +"+++++++++++");
System.out.println("1. Check Account Balance");
System.out.println("2. Deposit Checks");
System.out.println("3. Withdraw Money");
System.out.println("4. Logout");
System.out.print("\nWhat would you like to do next?\n");
}
public static void logout()
{
System.out.println("Thanks for usinging the David Vachlon Inc. ATM. We hope you expierence was fast and simple! Have a great day.");
System.exit(0);
}
public static double getBalance()
{
return balance;
}
public static void deposit()
{
balance+=deposit;
}
public static void withdraw()
{
balance-=withdraw;
}
}
You should do atm.balance -= atm.withdraw; after all checks was successfully passed. For instance, you may restructure your code as follows:
boolean ok = false;
while (!ok) {
System.out.println("\nHow much money will you be withdrawing? \n(Only amounts divisible by 20 are accepted)");
atm.withdraw = input.nextInt();
if (atm.withdraw % 20 != 0) {
System.out.println("Invalid withdraw amount. Please retry.");
} else if (atm.balance < atm.withdraw) {
System.out.println("You are not allowed to take out more then you have in your account \n Please retry");
} else if (atm.withdraw < 0) {
// Probably you should not allow to withdraw a negative amount of money
} else {
ok = true;
}
}
atm.balance -= atm.withdraw;
System.out.println("You took out " + atm.withdraw);
System.out.println("Your new balance is $" + atm.balance);
I have had a good look in books and the internet but cannot find a solution to my specific problem.Im really worried as time is running out.
I am writing code for an account. Each transaction, if it is add or withdraw is an object. Information such as the add amount, withdraw amount, transaction number,balance and total spending in a particular category is an object. Each object is stored in an arrayList. There is also code for logging in because this will eventually be an app. It requires the user to input their student number(last 4 digits).
The code runs ok and it serializes on termination. Upon running the code i can see it has de serialized the file as there is a list of objects in the arrayList printed.
My problem is that the values such as student number and balance are 0 when the code runs.Also the transaction number does not increment. It does increment while the code runs but stops upon termination, starting at 1 when the code is run again.
I expected all values to be the same when de serailized as those in the last object in the arrayList before serialization.
I dont expect anyone to post the answer but if someone could point me in the right direction i could try to work it out myself.
Best regards
Richard
PS. transaction number is the first in the object, balance in the middle and student number the four digits at the end. I have added the main class and serialization class, if anyone wants to see the login, transaction or other classes i can post these too.
`
/**
* Created by Richard on 16/07/2014.
*/
public class AccountTest implements Serializable {
public static Scanner keyboard = new Scanner(System.in);
//Declare an ArrayList called 'transactions' which will hold instances of AccountInfo.
public static ArrayList transactions = new ArrayList<AccountInfo>();
//Declare and initiate variables relating to the AccountTest class.
private static int transactionNum = 0;
private static double depositAmount = 0;
public static double withdrawAmount = 0;
private static double currentBalance = 0;
// A method which prompts the user to either withdraw, add funds or quit,
//this method also updates the balance and transaction number.
public static void addOrSpend() {
do {//A do while loop to ensure that the method repeatedly asks the user for input.
System.out.println("Enter a 1 to deposit, 2 to withdraw, 3 to terminate:");
int choice = keyboard.nextInt();
if (choice == 1) {//The deposit choice that also sets transaction no. and the balance.
System.out.println("Enter an amount to deposit ");
depositAmount = keyboard.nextInt();
transactionNum = transactionNum + 1;
withdrawAmount = 0;
currentBalance = currentBalance + depositAmount;
//System.out.println("You entered: " + depositAmount);
}//if
if (choice == 2) {//The withdraw choice that also sets transaction num, balance and calls chooseCategory method.
System.out.println("Enter an amount to withdraw ");
withdrawAmount = keyboard.nextInt();
transactionNum = transactionNum + 1;
depositAmount = 0;
currentBalance = currentBalance - withdrawAmount;
AccountCategory.chooseCategory();
}//if
if (choice == 3) {//User option to quit the program.
AccountSerialize.serialize();
System.out.println("App terminated...");
System.exit(1);
}//if
AccountInfo acc = new AccountInfo();//creates an object of the AccountInfo class
//Setters for the various methods in the AccountInfo class,
// these initiate variables for instances of the class.
acc.setTransactionNum(transactionNum);
acc.setDepositAmount(depositAmount);
acc.setWithdrawAmount(withdrawAmount);
acc.setCurrentBalance(currentBalance);
acc.setAccommodation(AccountCategory.accommodation);
acc.setTransport(AccountCategory.transport);
acc.setUtilities(AccountCategory.utilities);
acc.setEntertainment(AccountCategory.entertainment);
acc.setEssentials(AccountCategory.essentials);
acc.setStudentNo(AccountLogin.studentNo);
transactions.add(acc);//Adds each new 'acc' object to the ArrayList 'transaction'.
//System.out.println("List:" + transactions);Unused print statement which shows contents of ArrayList for testing.
Formatter x = new Formatter();//Series of formatted print statements which allow the information to be displayed in tabular format with headings.
System.out.println(String.format("%-20s %-20s %-20s %-20s ", "Transaction No.", "Deposit amount", "Withdraw amount", "Current balance"));
System.out.println(String.format("%-20s %-20s %-20s %-20s", transactionNum, depositAmount, withdrawAmount, currentBalance));
System.out.println(String.format("%-20s %-20s %-20s %-20s %-20s ", "Accommodation", "Transport", "Utilities", "Entertainment", "Essentials"));
System.out.println(String.format("%-20s %-20s %-20s %-20s %-20s", AccountCategory.accommodation, AccountCategory.transport, AccountCategory.utilities,
AccountCategory.entertainment, AccountCategory.essentials));
} while (transactions.size() >= 0);//End of do while statement that repeatedly prompts the user.
}
//Main method from where the program starts and user logs in. Starts with request for user to login.
// This then allows the user to continue with the program.
public static void main(String args[]) {
AccountSerialize.deSerialize();
System.out.println("Testing to see if student num is saved, login is..." +AccountLogin.studentNo );
System.out.println("Testing to see if balance is saved, balance is..." +currentBalance );
if (AccountLogin.studentNo == 0)
{
AccountLogin.numberSave();
}
else
{
AccountLogin.login();
}
}//main
}//class AccountTest
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Richard on 24/07/2014.
*/
public class AccountSerialize {
public static String filename = "budgetApp.bin";
public static String tmp;
public static void serialize() {
try {
FileOutputStream fos = new FileOutputStream("budgetApp.bin");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(AccountTest.transactions);
oos.close();
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Done writing");
}//serialize()
public static void deSerialize(){
try
{
FileInputStream fis = new FileInputStream("budgetApp.bin");
ObjectInputStream ois = new ObjectInputStream(fis);
AccountTest.transactions = (ArrayList) ois.readObject();
ois.close();
fis.close();
}catch(IOException ioe){
ioe.printStackTrace();
return;
}catch(ClassNotFoundException c){
System.out.println("Class not found");
c.printStackTrace();
return;
}
for( Object tmp:AccountTest.transactions){
System.out.println(tmp);
}
}//deSerialize()
}//class
import java.util.Scanner;
/**
* Created by Richard on 22/07/2014.
*/
public class AccountCategory {
static Scanner keyboard = new Scanner(System.in);
//Declare and initiate variable to be used in this class.
public static double accommodation = 0;
public static double transport = 0;
public static double utilities = 0;
public static double entertainment = 0;
public static double essentials = 0;
//A method which prints a set of spending category choices and asks the user to choose.
//Also updates each category variable with the total amount spent in that category
public static void chooseCategory() {
System.out.println("Please choose a category of spending, enter corresponding number");
System.out.println("1:\tAccommodation \n2:\tTransport \n3:\tUtilities \n4:\tEntertainment " +
"\n5:\tEssentials ");
double choice = keyboard.nextInt();//User input.
if (choice == 1) {
accommodation = accommodation + AccountTest.withdrawAmount;
}//if
if (choice == 2) {
transport = transport + AccountTest.withdrawAmount;
}//if
if (choice == 3) {
utilities = utilities + AccountTest.withdrawAmount;
}//if
if (choice == 4) {
entertainment = entertainment + AccountTest.withdrawAmount;
}//if
if (choice == 5) {
essentials = essentials + AccountTest.withdrawAmount;
}//if
}//chooseCategory
}//Class AccountCategory
import java.io.Serializable;
import java.util.Scanner;
/**
* Created by Richard on 16/07/2014.
*/
public class AccountInfo implements Serializable {
//Declare variables for types of transaction, balance and categories of spending.
public int studentNo;
public int transactionNum;
public double depositAmount;
public double withdrawAmount;
public double currentBalance;
public double accommodation;
public double transport;
public double utilities;
public double entertainment;
public double essentials;
//Series of mutator methods which take and validate the user input from the Test class, setting new variable values
//for objects of this AccountInfo class.
public void setStudentNo(int studentNo) {
this.studentNo = studentNo;
}
public void setTransactionNum(int transactionNum) {
this.transactionNum = transactionNum;
}
public void setDepositAmount(double depositAmount) {
this.depositAmount = depositAmount;
}
public void setWithdrawAmount(double withdrawAmount) {
this.withdrawAmount = withdrawAmount;
}
public void setCurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
}
public void setAccommodation(double accommodation) {
this.accommodation = accommodation;
}
public void setTransport(double transport) {
this.transport = transport;
}
public void setUtilities(double utilities) {
this.utilities = utilities;
}
public void setEntertainment(double entertainment) {
this.entertainment = entertainment;
}
public void setEssentials(double essentials) {
this.essentials = essentials;
}
//A toString method to ensure printed information is user readable
public String toString() {
return "AccountInfo[" + transactionNum + "," + depositAmount + "," + withdrawAmount + "," + currentBalance + "," +
accommodation + "," + transport + "," + utilities + "," + entertainment + "," + essentials + ","+studentNo+"]";
}//toString
}//class AccountInfo
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Created by Richard on 20/07/2014.
*/
public class AccountLogin {
public static Scanner keyboard = new Scanner(System.in);
//Declare and initiate variables.
public static int studentNo=0;
public static int login=0;
public static void login() {
if (studentNo > 0 && Integer.toString(studentNo).length() == 4)//Validation test.
{
System.out.println("Log in with last four digits of your student number:");
login = keyboard.nextInt();//User input.
}//if
if(login==studentNo){
AccountTest.addOrSpend();//If validated
}//if
else{
enterNoAgain();
}//else
}//login()
//This method checks to see if the user has already entered and saved their details, if not the user is prompted to do so.
//If the user has already entered their details
public static void numberSave() {
if (studentNo == 0) {//Checks to see if student number has already been entered.
System.out.println("Enter and save the last four digits of your student number, use this to login to the Budgeting app:");
studentNo = keyboard.nextInt();//User input.
if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Checks that user input meets requirements.
System.out.println("You are now logged in:");
AccountTest.addOrSpend();//Program starts at this point once user input is validated.
}//if
else {//If user input does not meet criteria, the following method is called.
enterNoAgain();
}//else
}//if
}//numberSave()
// This method takes over if the user has not input valid data.
// The user is instructed to do so and is given a further 2 opportunities before the program exits
public static void enterNoAgain() {
System.out.println("Invalid input: Use 4 numbers only, try again");//Prompt.
studentNo = keyboard.nextInt();//User input.
if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Validation test.
AccountTest.addOrSpend();//If validated
}//if
else {
System.out.println("Last attempt, input last four digits of your student number");//Prompt.
studentNo = keyboard.nextInt();//User input.
if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Validation test.
AccountTest.addOrSpend();//If validated
}//if
else {
AccountSerialize.serialize();//Save to file
System.out.println("You failed to login");
System.out.println("App terminated...");
System.exit(1);//Program exits due to invalid user input.
}//else
}//else
}//enterNoAgain()
}//class AccountLogin
`
AccountTest
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,50.0,0.0,50.0,0.0,0.0,0.0,0.0,0.0,3333]
AccountInfo[1,50.0,0.0,50.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,6666]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,50.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,500.0,0.0,500.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,0.0,0.0,50.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,50.0,0.0,0.0,0.0,0.0,1234]
Testing to see if student num is saved, login is...0
Testing to see if balance is saved, balance is...0.0
Enter and save the last four digits of your student number, use this to login to the Budgeting app:
1234
You are now logged in:
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
1
Enter an amount to deposit
1000
Transaction No. Deposit amount Withdraw amount Current balance
1 1000.0 0.0 1000.0
Accommodation Transport Utilities Entertainment Essentials
0.0 0.0 0.0 0.0 0.0
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
2
Enter an amount to withdraw
50
Please choose a category of spending, enter corresponding number
1: Accommodation
2: Transport
3: Utilities
4: Entertainment
5: Essentials
1
Transaction No. Deposit amount Withdraw amount Current balance
2 0.0 50.0 950.0
Accommodation Transport Utilities Entertainment Essentials
50.0 0.0 0.0 0.0 0.0
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
3
Done writing
App terminated...
Process finished with exit code 1
package developer;
import java.util.*;
import java.lang.Math.*;
public class Developer
{
static Scanner console = new Scanner(System.in);
String workType; // This will be either an app, or game
String name;
int pay;
int weekPay;
int hrsWorked;
double tax;
public Developer()
{
name = "Ciaran";
}
Developer(String appType, String coderName)
{
workType = appType;
name = coderName;
}// End developer
Developer(String appType, int pay) // Class to choose the pay rate depending on if it is a game or app
{
System.out.println("Are you coding an app or a game? ");
appType = console.next();
if(appType == "app")
{
pay = 20;
}
if(appType == "game")
{
pay = 30;
}
else
{
System.out.println("Please enter either 'app' or 'game' ");
}
}// End developer
Developer(int hrsWorked, double tax, int weekPay, int pay) // Class to choose the tax bracket which the developer is in
{
System.out.println("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
weekPay = hrsWorked * pay;
if(weekPay >= 865)
{
tax = 0.4;
}
else
{
tax = 0.21;
}
}// End developer
Developer(int weekPay, int tax) // Gets the pay after tax
{
weekPay = weekPay * tax;
}// End developer
public void display()
{
System.out.println("This display method works");
System.out.println("User: " + name);
}
public static void main(String[] args)
{
Developer myDev = new Developer();
myDev.display();
} // End main
}// End public class developer
I am trying to get this program to ask the user what their name is; if they are developing a game or app and the amount of hours worked on it. With all this information I want to calculate how much the dev earns including tax. I cannot seem to get the display() method to ask the user the questions though and I have no idea what to do. I am hoping somebody out there can help me.
System.in will read input from the command line. You should wrap it with a java.util.Scanner and nextLine like this:
Scanner scanner = new Scanner(System.in);
String user_input = scanner.nextLine();
Be sure to check
scanner.hasNextLine()
before continuing or you'll get an error.
There are few things that could be done differently in your code, so let's break it down:
1.No need to make console static type, you can use:
private Scanner console = new Scanner(System.in);
2.weekPay is of type int, but your tax is double, if you don't want weekPay to be cast to integer, change it to:
double weekPay;
3.Later on, you are calculating weekPay after tax, so let's introduce a variable for that:
double weekPayAfterTax;
4.All these Developer() methods are constructors, and I think you are slightly confused here. Of course, you can have many constructors, but for us, let's keep only the no-params constructor:
public Developer() {
name = "Ciaran";
//you could initialise all the other variables here as well,
//I'll leave it as an exercise for you :)
}
5.Let's create a method that will ask all the questions and set respective variables:
void setData() {
//let's get the name
System.out.print("What's your name: ");
name = console.nextLine();
System.out.print("Are you coding an app or a game? ");
//since we want the user to enter 'app' or 'game'
//we need to loop until we got these
//we can do this by creating endless while loop,
//which we will end when we have correct input
while (true) {
workType = console.next();
if (workType.equals("app")) {
pay = 20.0;
//stop the loop
break;
}
else if (workType.equals("game")) {
pay = 30.0;
//stop the loop
break;
}
else {
System.out.print("Please enter either 'app' or 'game': ");
//back to top
}
}
//ok, we're out the loop, let's get number of hours
System.out.print("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
//calculate weekPay
weekPay = hrsWorked * pay;
if(weekPay >= 865) {
tax = 0.4;
}
else {
tax = 0.21;
}
//calculate pay after tax
weekPayAfterTax = weekPay - weekPay * tax;
}
6.Let's update our display() method to show all the info:
public void display() {
System.out.println("This display method works");
System.out.println("User: " + name);
System.out.println("Work type: " + workType);
System.out.println("Pay: " + pay);
System.out.println("Week pay: " + weekPay);
System.out.println("Week pay after tax: " + weekPayAfterTax);
}
7.In your main method, you can finally create an instance of Developer class and get the data:
public static void main(String[] args) {
Developer myDev = new Developer();
myDev.setData();
myDev.display();
}
The code above can be improved (such as checking if user entered number where it's expected), and your problem can of course be done differently, but here's the start.
Please check out some tutorials to learn the basics, such as this one, or this one. Most of all, experiment and don't let others put you down for not understanding something.
My code is supposed to simulate something similar to a vending machine. But there is a problem when I enter a price that is not one of my options, e.g. 0.82 the program still runs. How do I get it to only accept one of my options?
import java.util.Scanner;
public class VendingMachine
{
public static void main (String[] args)
{
double price;
Scanner keyboard = new Scanner(System.in);
System.out.println("Choose your price. Your options are: ");
double i;
for (i=0.25; i<=1.25; i+=0.25)
System.out.printf("$%.2f\n", i );
System.out.println("Enter your selection now: ");
price=keyboard.nextDouble();
System.out.printf("You chose the $%.2f option. ",price);
double deposit;
if (price<=1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit=1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit=2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit-price;
System.out.printf("Your change is $%.2f\n",change);
}
}
I tried something like this but it doesn't work. What is the best way to do this.
if (price==i)
System.out.println("You entered " + price);
else {
System.out.println("Invalide choice. Please try again.")
System.exit(0);
}
Here is an image if you find it easier to read.
You can use some sort of loop (while, do-while, for), which will continue to excecute the code until a condition is (or isn't) met.
Here is an example:
do {
code line 1;
code line 2;
code line 3;
...
} while(yourCondition);
If yourCondition is satisfied (yourCondition == true), the code will go back to code line 1 (will perform the code block between do and while) and it'll stop once the condition isn't satisfied(yourCondition == false). yourCondition could be any expression that returns a true/false result (boolean), such as 2+2==4.
If you want to keep looping for as long as yourCondition isn't met, you can add a ! before your expression, which will evaluate the opposite of your boolean like this (!yourCondition).
Now, if you understood how that works, you can easily apply it to your code.
If you want the user to enter only your displayed prices, I suggest the following, you shall edit to your exact desires.
//given you an open scanner
boolean isCorrectPrice = false;
System.out.println("enter price");
price = in.nextDouble();
while(!isCorrectPrice)
{
if(price%0.25==0 && price<=1.25 && price>0)
{
System.out.println("you entered "+price);
IsCorrectPrice = true;
continue;
}
System.out.println("incorrect price, re-enter ");
price = in.nextDouble();
}
//your code after user enters correct price
That will do the check. If your prices change, all you have to do is change the maximum price provided its still dividable with 0.25 or the condition price check.
Use BigDecimal (instead of double) to work with money. Its exact -- double isn't.
http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html
I would write a function to get the user input. It would not return until the
user had entered an allowed value.
Although my real answer is the one on the comments, you can use something like this. To check recursively if the correct value was given.
import java.util.Scanner;
public class VendingMachine {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Choose your price. Your options are: ");
for (double i = 0.25; i <= 1.25; i += 0.25) {
System.out.printf("$%.2f\n", i);
}
double price = checkMultipleValues(0.25,1.25, 0.25);
System.out.printf("You chose the $%.2f option. ", price);
double deposit;
if (price <= 1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit = 1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit = 2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit - price;
System.out.printf("Your change is $%.2f\n", change);
}
private static double checkMultipleValues(double initial,double last,double step) {
System.out.println("Enter your selection now: ");
double price = keyboard.nextDouble();
for (double i = initial; i <= last; i += step) {
if (price == i) {
return price;
}
}
return checkMultipleValues( initial, last, step);
}
}
ADDENDUM
Since you like #Sello answer why don't you combine it with #MrD and have something like
do {
System.out.println("enter price");
price = in.nextDouble();
// System.out.println("you entered " + price);
} while (!(price % 0.25 == 0 && price <= 1.25 && price > 0));