I have this bit of code to return to the beginning of the program if an answer is not expected.
...
else // returns to start for unsatisfactory
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
}
...
however when I enter a different word then go through again and enter an expected word the program outputs two different results
Current Salary: $100.00
Amount of your raise: $4.00
Your new salary: $104.00
Current Salary: $100.00
Amount of your raise: $0.00
Your new salary: $100.00
I tried using an else if statement to possibly eliminate that as a cause but it caused the same thing.
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary {
public static void main (String[] args) {
double currentSalary; // employee's current salary
double raise = 0.0; // amount of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
// Computes raise with if-else
if ((rating.equals("Excellent")) || (rating.equals("excellent"))) {
// calculates raise for excellent
raise = .06 * currentSalary;
}
else if ((rating.equals("Good")) || (rating.equals("good"))) {
// calculates raise for good
raise = .04 * currentSalary;
}
else if ((rating.equals("Poor")) || (rating.equals("poor"))) {
// calculates raise for poor
raise = .015 * currentSalary;
}
else {
// returns to start for unsatisfactory
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
}
newSalary = currentSalary + raise;
// Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
That is because you call main recursively (which is not considered good practice BTW) when you don't get an expected input. After you enter (the 2nd time) an expected input, the remainder of the initial main must still be executed which will then work with a raise of 0.0 as the input was invalid.
A pragmatic solution for your issue could be avoiding the recursive call to main and wrap e.g. the input validation in a loop like so
...
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
while (true) {
rating = scan.next();
if ((rating.equals("Excellent")) || (rating.equals("excellent")))
{
raise = .06 * currentSalary; break;
}
else if ((rating.equals("Good")) || (rating.equals("good")))
{
raise = .04 * currentSalary; break;
}
else if ((rating.equals("Poor")) || (rating.equals("poor")))
{
raise = .015 * currentSalary; break;
}
else
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
}
}
...
You're not returning after you call main (args); so every iteration of your program will continue.
You should add return; after main (args);
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
return;
}
edit: as pointed out by John3136 you shouldn't be calling main (args) recursively either.
That (second) call you make to main() "finishes" and comes back out to the "first" one that was invoked by starting the program.
So the first lot of results are from your explicit call to main(). The second lot is from when that call ends and you are back to where you called from.
Calling main() recursively is not recommended. You should use a while loop inside main(). i.e. Keep asking for input until you know the input is valid, and then actually use it.
You should not call main recursively.you should use do while loop as I update code and it's working fine.
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary {
public static void main (String[] args) {
double currentSalary; // employee's current salary
double raise = 0.0; // amount of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
boolean flag=false; // to check input
Scanner scan = new Scanner(System.in);
do{
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
// Computes raise with if-else
if ((rating.equals("Excellent")) || (rating.equals("excellent"))) // calculates raise for excellent
{
raise = .06 * currentSalary;
flag=true;
}
else if ((rating.equals("Good")) || (rating.equals("good"))) // calculates raise for good
{
raise = .04 * currentSalary;
flag=true;
}
else if ((rating.equals("Poor")) || (rating.equals("poor"))) // calculates raise for poor
{
raise = .015 * currentSalary;
flag=true;
}
else // returns to start for unsatisfactory
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
flag=false;
}
}while(!flag);
newSalary = currentSalary + raise;
// Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
You may want to consider another approach. Either terminate the problem in case the input is invalid or try to repair it. The following example is for the "repair" approach,
public class Salary {
public static void main(String[] args) {
IPM ipm;
if (verify(args)) {
ipm = new IPM(args);
} else {
Scanner scan = new Scanner(System.in);
String[] update;
do {
update = repair(scan);
} while (!verify(update)); // You may want a loop count as well...
ipm = new IPM(update);
}
ipm.print();
}
public static boolean verify(String[] s) {
return IPM.verify(s);
}
public static String[] repair (Scanner s) {
// Request new input and store it in an array of strings.
// This method does not validate the input.
}
}
public class IPM {
double currentSalary;
double raise = 0.0;
double newSalary;
String rating;
IPM(String[] input) {
// Set attributes of IPM.
}
public static boolean verify(String[] s) {
//Determine if the input is valid.
}
public void print() {
// Print IPM object.
}
}
Note that the call to IPM.verify() from salary. This should be a part of the responsibility of IPM since Salary is not require to know anything about main. Also, the class IPM might change and a call to IPM.verify() will not require that all classes which verifies the IPM are changed as well.
Related
I want it to start again at the most outer for loop, so that if a user messes up the input, they can sign in again and everything work just like if the program started all over again. I tried using continue statements and break statements and using the nicknames for the loops. Like
outer: do {
//loop code
}
then break outer;
The problem is when I do that, it messes up my controlling of the loop. The end statement that asks the user if they want to go back to the main menu. Right now I just have the app exit, if an exception is encountered, using return statement, but If I'm just gonna exit, I might as well just let the app crash. I want to actually resolve the situation and ask the user for valid input.
package main;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Scanner;
import model.BankAccount;
public class app {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
HashMap<String, BankAccount> accounts = new HashMap<>();
BankAccount sallyAccount = new BankAccount(1000);
BankAccount bobAccount = new BankAccount(2000);
BankAccount naomiAccount = new BankAccount();
accounts.put("Sally", sallyAccount);
accounts.put("Bob", bobAccount);
accounts.put("Naomi", naomiAccount);
String name;
BankAccount account;
int userInput;
double amount;
boolean again;
do
{
again = true;
System.out.println("Login: Enter your name.");
name = console.next();
account = accounts.get(name);
if(account == null)
{
System.out.println("Please enter a valid name.");
return;
}
do
{
System.out.println("1 - Deposit");
System.out.println("2 - Withdraw");
System.out.println("3 - View Balance");
System.out.println("4 - Logout");
userInput = console.nextInt();
switch(userInput)
{
case 1:
System.out.println("Enter amount to deposit: ");
try
{
amount = console.nextDouble();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a numeric amount.");
return;
}
if(amount < 0)
{
System.out.println("You can't withdraw a negative amount");
return;
}
account.deposit(amount);
break;
case 2:
System.out.println("Enter amount to withdraw: ");
try
{
amount = console.nextDouble();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a numeric amount.");
return;
}
if(amount < 0)
{
System.out.println("You can't withdraw a negative amount");
return;
}
account.withdraw(amount);
break;
case 3:
System.out.println(account.getBalance());
break;
case 4:
again = false;
break;
default:
System.out.println("Enter a valid option.");
}
}
while(again);
System.out.println("Back to main menu? 1 - Yes, 2 - No");
try
{
userInput = console.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a number");
return;
}
}
while(userInput == 1);
}
}
package model;
public class BankAccount {
private double balance = 0;
public BankAccount() {}
public BankAccount(double balance)
{
this.balance = balance;
}
public void deposit(double amount)
{
balance = balance + amount;
}
public void withdraw(double amount)
{
if((balance - amount) < 0)
{
System.out.println("Transaction Failed: You can't withdraw more than you have.");
}
else
{
balance = balance - amount;
}
}
public double getBalance()
{
return balance;
}
}
You'll be best served by breaking up your main function in multiple functions that handle different parts of the control logic. A good rule of thumb (for beginning programmers) is a function over ~10-15 lines should probably be multiple functions, though it's not an ironclad rule.
I rewrote your program to be multiple functions, but since this seems like a homework problem I won't post the whole thing. Rather, a general strategy with some snippets.
For example, when the user enters an amount to deposit or withdraw. What your programs wants in that moment is a single double, so you could request a single double, and let another method figure out how to get it:
switch (getMenuChoice()) {
case 1:
account.deposit(getDepositOrWithdrawAmount("deposit"));
break;
case 2:
account.withdraw(getDepositOrWithdrawAmount("withdraw"));
break;
// etc.
}
Then, that function is responsible for looping infinitely until the user provides a valid value:
static double getDepositOrWithdrawAmount(String depositOrWithdraw) {
// loop infinitely until we get a valid value
while (true) {
System.out.println("Enter amount to " + depositOrWithdraw);
try {
double amount = console.nextDouble();
if (amount < 0) {
System.out.println("You can't " + depositOrWithdraw + " a negative amount.");
} else {
// valid value! return for deposit / withdraw to use
// , ending the infinite loop
return amount;
}
} catch (InputMismatchException e) {
System.out.println("Please enter a numeric amount.");
// clear the bad token from the stream
// if you don't do this, each time you
// call `nextDouble`, the same value will
// be returned, causing an infinite loop
console.next();
}
}
}
The nice thing about this function is it works in isolation:
public static void main(String[] args) {
System.out.println("Test: " + getDepositOrWithdrawal("test!"));
}
Gives this result:
Enter amount to test!
abc
Please enter a numeric amount.
Enter amount to test!
not-a-number
Please enter a numeric amount.
Enter amount to test!
-5
You can't test! a negative amount.
Enter amount to test!
1000
Test: 1000.0
This lets you test that pieces of your program are working on their own, instead of trying to debug one big program.
You can write other parts of your program as functions as well, but I'll leave that to you.
i am new to programming, and i was wondering if i could get some help. My program stops running at System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");. I am open to any suggestion. Also, please point out anything else wrong with this program. Thanks!
import java.util.Scanner;
public class Interest
{
double userInput;
double interest;
double time;
double amount;
double answer;
Scanner myScanner = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");
}
{
System.out.println("Please enter your percent of interest in a decimal format: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
interest = userInput;
}
else
{
System.out.println("Please enter a integer for your percent of interest.");
}
}
{
System.out.println("Please enter the time the interest is applied for: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
time = userInput;
}
else
{
System.out.println("Please enter an integer for the time the interest is applied for.");
}
}
{
System.out.println("Please enter your amount of money that the interest is applied to: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
amount = userInput;
}
else
{
System.out.println("Please enter an integer for the amount of money that the interest is applied to.");
}
}
{
answer = (amount * interest * time);
}
{
System.out.println("Your interest is $" + answer + ".");
System.out.println("Your total payment is $" + (answer + amount) + ".");
}
}
Get rid of all the extra braces; they're outside your main method.
public static void main(String[] args)
{
System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");
// } <-- remove
// { <-- remove
System.out.println("Please enter your percent of interest in a decimal format: ");
// -----SKIP-----
// } <-- remove
// { <-- remove
System.out.println("Your interest is $" + answer + ".");
System.out.println("Your total payment is $" + (answer + amount) + ".");
} // leave this here (end of method)
you are writing instance blocks and in main method,you did not make object creation.instance blocks are executed when you create object of class.if you want to execute those instance block you should write YourClass myclass = new YourClass()in your main method and when you run main function,those blocks outside of main()will be executed OR you should write these blocks in main method just like #shmosel's example.
public class Salary
{
public static void main (String[] args)
{
double currentSalary; // employee's current salary
double raise; // amount of the raise
double percentRaise; // percentage of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
if (rating.equals("Excellent"))
percentRaise = .06;
raise = (.06 * currentSalary);
else if (rating.equals("Good"))
percentRaise = .04;
raise = (.04 * currentSalary);
else if (rating.equals("Poor"))
percentRaise = .015;
raise = (.015 * currentSalary);
//Compute the raise using if ...
newSalary = currentSalary + raise;
//Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println( "Your new salary: " + money. format (newSalary) );
System.out.println();
scan.close();
}
}
if i add { and } where the whitespace is then it says raise is not initialized. No matter what i do i cant seem to figure out to get it running. Right now it tells me to delete the else to let it run but if i do no matter i write excellent, good, or poor. It does .015 * salary so i cant get excellent or good to run.
if (rating.equals("Excellent"))
percentRaise = .06;
raise = (.06 * currentSalary);
else if (rating.equals("Good"))
Won't compile because Java sees this as...
if (rating.equals("Excellent"))
percentRaise = .06;
raise = (.06 * currentSalary);
else if (rating.equals("Good"))
Meaning that the compiler will complain about the else-if without a if statement.
The other problem you're having (when you place { } around the statements) is because Java makes no determination about what the initial value of a local variable will have.
This means Java simply doesn't know what to do with newSalary = currentSalary + raise; as there is no guarantee that raise will have a value assigned to it.
You could overcome this by adding an else condition to the end of your if-else block or simply supplying an initial value to your local variables...
double currentSalary = 0; // employee's current salary
double raise = 0; // amount of the raise
double percentRaise = 0; // percentage of the raise
double newSalary = 0; // new salary for the employee
String rating = ""; // performance rating
And while it might seem annoying, it's better then getting some completely random value which you would have to spend time trying to debug ;)
Updated
Remember, String#equals is case sensitive, this means "Excellent" is not equal to "excellent".
You could use String#equalsIgnoreCase instead
You need to wrap if statements into these things ---> "{}"
so its like this:
if(statement){
//then do someting
}else{
//then do something else
}
You can only write if statements without braces if it contains only one command, if you have more than one command (more than one line) you need to enclose those commands in braces
You have to make sure that if your if statement contains more than one line of code, it is wrapped in braces.
public class Salary
{
public static void main (String[] args)
{
double currentSalary; // employee's current salary
double raise; // amount of the raise
double percentRaise; // percentage of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
if (rating.equals("Excellent"))
{
percentRaise = .06;
raise = (.06 * currentSalary);
}
else if (rating.equals("Good"))
{
percentRaise = .04;
raise = (.04 * currentSalary);
}
else if (rating.equals("Poor"))
{
percentRaise = .015;
raise = (.015 * currentSalary);
}
//Compute the raise using if ...
newSalary = currentSalary + raise;
//Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println( "Your new salary: " + money. format (newSalary) );
System.out.println();
scan.close();
}
}
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));