//deposit case
case "deposit":
JOptionPane.showMessageDialog(null,"We accept the following dollar bills:\n1, 5, 10, 20, 50, 100"
+ "\nPlease insert the bill on the console."
+ "\nEnter any other number to stop depositing."
,"Insert Bill",JOptionPane.INFORMATION_MESSAGE);
System.out.println("Insert bills here.");
int deposit = keyboard.nextInt();
int total = 0;
while (deposit==1||deposit==5||deposit==10||deposit==20||deposit==50||deposit==100)
{
total += deposit;
//System.out.println(deposit);
deposit = keyboard.nextInt();
//System.out.println(deposit);
keyboard.close();
// if (deposit!=1||deposit!=5||deposit!=10||deposit!=20||deposit!=50||deposit!=100)
// {
// break;
// }
}
acc.deposit(total);
JOptionPane.showMessageDialog(null, "You deposited "+total+" dollars."
+"\nThe current balance is: $"+acc.showBalance()
,"Deposit into Account" ,JOptionPane.WARNING_MESSAGE);
break;
//withdraw case
case "withdraw":
int money = 0;
String moneyString = JOptionPane.showInputDialog(null,"Please enter amount you want to withdraw"
,"Withdraw from Account",JOptionPane.QUESTION_MESSAGE);
if (moneyString == null||moneyString.length()==0)
{
money = 0;
}
else {
money = Integer.parseInt(moneyString);
}
acc.withdraw(money);
break;
It seems that you close out your scanner keyboard after you use it the first time in the loop and never open it again. Try to close your scanner just before closing the program or after all deposits have been completed.
I figured the issue. I'm on a Mac and my JOptionPane windows were popping up behind my editor. Sorry, this post is useless.
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");
}
}
When user input value pay rate, it will check the value pay rate with the array of pay rate. If correct then it will prompt if user has another process need to be done. If not, it will go to calculation.
If the pay rate is wrong, then it will display wrong and ask the user to enter value again.
I have problems where after user press the 'Y' it will display 'the wrong pay rate, please try again'.
public static void main(String[] args) {
//Scanner
Scanner read = new Scanner(System.in);
//Array of payRate Default
double[] payRateDefault = {3.50, 4.00, 4.50, 4.75, 5.00, 5.25, 5.50, 5.75, 6.00};
double payRateEntered;
boolean isPayRate = false;
char anotherProcess;
System.out.print("Enter hours work: ");
int hoursWork = read.nextInt();
do {
System.out.print("Enter pay rate: ");
payRateEntered = read.nextDouble();
for (int i = 0; i < payRateDefault.length; i++) {
if (payRateDefault[i] == payRateEntered) {
//If the payRate is true with array payRateDefault, proceed to ask if you have another employee
System.out.println("Do you have any employee to process (Y/N)");
anotherProcess = read.next().charAt(0);
isPayRate = true;
//Check if Y or N
switch (anotherProcess) {
case 'Y':
//Proceed back to prompt user to enter pay rate
break;
case 'N':
//Proceed to calculation
break;
default:
//If wrong input
System.out.println("Please use Y or N only");
break;
}
} else {
isPayRate = false;
}
}
System.out.println("You have entered the wrong pay rate. Please try again");
} while (!isPayRate);
}
Result:
The following code works fine for me:
package mm.com.java.so.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaRepeat {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
double[] defaultPayRates = { 3.50, 4.00, 4.50, 4.75, 5.00, 5.25, 5.50, 5.75, 6.00 };
double payRate;
boolean isValid;
boolean isContinue;
String next;
int workingHour;
do {
isValid = false;
isContinue = false;
System.out.print("\nEnter hours work : ");
workingHour = Integer.parseInt(reader.readLine());
do {
System.out.print("Enter pay rate: ");
payRate = Double.parseDouble(reader.readLine());
for (int i = 0; i < defaultPayRates.length; i++) {
if (defaultPayRates[i] == payRate) {
isValid = true;
// TODO : make calculation here.
break;
}
}
if (!isValid) {
System.out.println("You have entered the wrong pay rate. Please try again !!!");
}
} while (!isValid);
do {
isValid = true;
System.out.println("\nDo you have any employee to process (Y/N)");
next = reader.readLine();
switch (next.toLowerCase()) {
case "y":
isContinue = true;
break;
case "n":
isContinue = false;
break;
default:
isValid = false;
System.out.println("Please use Y or N only.");
break;
}
} while (!isValid);
} while (isContinue);
// TODO : print out calculation here.
System.out.println("\nCalculation is doing. Please wait...");
}
}
My test results is as follows:
Enter hours work : 3
Enter pay rate: 2
You have entered the wrong pay rate. Please try again !!!
Enter pay rate: 5
Do you have any employee to process (Y/N)
y
Enter hours work : 2
Enter pay rate: 5
Do you have any employee to process (Y/N)
z
Please use Y or N only.
Do you have any employee to process (Y/N)
N
Calculation is doing. Please wait...
You should execute the System.out.println("You have entered the wrong pay rate. Please try again"); line, only if isPayRate is false.
boolean finished = false;
do {
System.out.print("Enter pay rate: ");
payRateEntered = read.nextDouble();
for (int i = 0; i < payRateDefault.length; i++) {
if (payRateDefault[i] == payRateEntered) {
//If the payRate is true with array payRateDefault, proceed to ask if you have another employee
System.out.println("Do you have any employee to process (Y/N)");
anotherProcess = read.next().charAt(0);
isPayRate = true;
//Check if Y or N
switch (anotherProcess) {
case 'Y':
//Proceed back to prompt user to enter pay rate
break;
case 'N':
//Proceed to calculation
finished = true;
break;
default:
//If wrong input
System.out.println("Please use Y or N only");
break;
}
break;
} else {
isPayRate = false;
}
}
if (!isPayRate) {
System.out.println("You have entered the wrong pay rate. Please try again");
}
} while (!finished);
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
}
}
I need to be able to press 'q' in the while loop to get it to exit the loop. I then need the code to be able to display the credit hours with the grade beside it. Next I have to display their GPA according to the input of their hours and their grades. Everytime I press 'q' to exit, the program stops and doesn't display anything. Please help!
package shippingCalc;
import javax.swing.JOptionPane;
public class Gpa {
public static void main(String[] args) {
String input = "";
String let_grade;
int credits = 0;
double letterGrade = 0;
int course = 1;
String greeting = "This program will calculate your GPA.";
JOptionPane.showMessageDialog(null, greeting,"GPA Calculator",1);
while(!input.toUpperCase().equals("Q"))
{
input = JOptionPane.showInputDialog(null, "Please enter the credits for class " + course );
credits = Integer.parseInt(input);
course ++;
input = JOptionPane.showInputDialog(null,"Please enter your grade for your " +credits + " credit hour class");
let_grade = input.toUpperCase();
char grade = let_grade.charAt(0);
letterGrade = 0;
switch (grade){
case 'A': letterGrade = 4.00;
break;
case 'B': letterGrade = 3.00;
break;
case 'C': letterGrade = 2.00;
break;
case 'D': letterGrade = 1.00;
break;
case 'F': letterGrade = 0.00;
break;
}
}
JOptionPane.showMessageDialog(null, course++ + "\n\n It Works" + letterGrade);
}
}
The issue I think is that credits is an int and right after the second popup
input = JOptionPane.showInputDialog(null,
"Please enter the credits for class " + course);
You assign whatever the user types to the int credits, so if you input a String q or Q its gonna break. Also, keep in mind that the while loop condition is only checked once per iteration, at the start of the iteration, so it won't know about the value of input until that time
There are a couple ways you could fix this. A quick and easy way would be to insert this line of code before assigning the user input to credit
if(input.equalsIgnoreCase("q")){
continue;//will allow input to be checked immediately before assigning to credits
}