I am currently learning Java and I am trying to retain the information I learned by building a ATM machine app (I plan on adding more to it in the future).
My current issue is I would like to ask a user 'What would you like to do' repeatedly until a valid input is provided(current valid inputs are 'Withdraw' and 'Deposit').
I have a loop that will repeatedly ask the user 'Please select a valid choice' if the input is not valid. If the input is valid it will execute only once, ask 'What would you like to do', and then display a NoSuchElementException. Not sure how to fix this.
Here is my code:
App.java
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("What woul you like to do?");
String response = scanner.next().toLowerCase();
Transactions newTransaction = new Transactions();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
} else if (response.equals("deposit")) {
newTransaction.Deposit();
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}
Transactions.java
import java.util.Scanner;
public class Transactions {
private int currentBalance = 100;
public void Withdrawal() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to withdraw?");
int withdrawAmount = scanner.nextInt();
if (withdrawAmount > 0) {
if (currentBalance > 0) {
currentBalance -= withdrawAmount;
System.out.println("Amount withdrawn: $" + withdrawAmount);
System.out.println("Current Balance: $" + Balance());
if (currentBalance < 0) {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println("Can't remove 0 from account");
}
scanner.close();
}
public void Deposit() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to deposit?");
int depositAmount = scanner.nextInt();
if (depositAmount > 0) {
currentBalance += depositAmount;
Balance();
}
System.out.println("Amount deposited: $" + depositAmount);
System.out.println("Current Balance: $" + Balance());
scanner.close();
}
public int Balance() {
return currentBalance;
}
}
Error Message
NoSuchElementException
You can use a sentinel. A sentinel is a value entered that will end the iteration.
//incomplete code showing logic
int choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice");
choice = input.nextInt();
while(choice != -1){ //-1 is the sentinel, can be value you choose
//Some logic you want to do
System.out.println("Enter choice or -1 to end");
choice = input.NextInt(); //notice we input choice again here
}
Like has been said you should learn about loops. There are two types while-loop and for-loop. In this case you should youse the while-loop.
The implementation of your problem could be this.
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("What woul you like to do?");
String response;
Transactions newTransaction = new Transactions();
while (true) {
response = scanner.next().toLowerCase();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
break;
} else if (response.equals("deposit")) {
newTransaction.Deposit();
break;
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}
Related
So the scenario is to limit a user to perform three transactions a day, I wanted to finish the part where the exception is to be raised any help would be appreciated.
import java.util.Scanner;
class FundsNotAvailable extends Exception{
FundsNotAvailable(String s){
super(s);
}
}
class ExceededTransactionsLimit extends Exception{
ExceededTransactionsLimit(String s){
super(s);
}
}
class BankMethods {
String accName;
String accNumber;
Integer balance;
public Integer transactions = 0;
Scanner sc = new Scanner(System.in);
void AccOpen()
{
System.out.println("Enter Account Holder Name: ");
accName = sc.next();
System.out.println("Enter Account Number: ");
accNumber = sc.next();
System.out.println("Enter the Deposit amount: ");
balance = sc.nextInt();
}
void Deposit()
{
Integer amount;
System.out.println("Enter the Amount you wish to Deposit:");
amount = sc.nextInt();
balance = balance + amount;
}
void Withdrawal() throws FundsNotAvailable, ExceededTransactionsLimit
{
Integer amount;
System.out.println("Enter the Amount you wish to Withdraw:");
amount = sc.nextInt();
if (amount > balance)
{
throw new FundsNotAvailable("Insufficient Funds");
}
if(transactions > 3)
{
throw new ExceededTransactionsLimit("You have exceeded the daily transactions limit");
}
balance = balance - amount;
System.out.println(transactions);
}
void showBalance()
{
System.out.println("The Balance in your Account is:" + balance);
}
}
public class Bank
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BankMethods BM = new BankMethods();
BM.AccOpen();
Integer choice;
do {
System.out.println("Main Menu \n 1. Deposit \n 2. Withdraw \n 3. Show Balance \n 4. Exit");
System.out.println("Please Make A Choice:");
choice = sc.nextInt();
switch (choice) {
case 1:
BM.Deposit();
break;
case 2:
try {
BM.Withdrawal();
} catch (ExceededTransactionsLimit | FundsNotAvailable e) {
System.out.println(e.getMessage());
}
break;
case 3:
BM.showBalance();
break;
case 4:
System.out.println("Good Bye");
break;
}
}
while (choice != 4);
}
}
the condition transactions > 3 is working fine when i run it in the main class but isnt throwing an exception when i run it in the method i even tried to keep track of the transcations variable value and it kept increasing everytime i performed the withdraw operation.
Thank you (any help is appreciated)
no where in the code, value of transactions variable is getting updated.
Please add transactions++; in your Withdrawal() function and it will start working.
I'm writing this code for an ATM simulator, with deposit, withdrawal and balance inquiry functionality. The code needs to be written with methods and not switch statements.
My deposit method works, but I have issues with both the withdraw and balanceInquiry methods. I would like to have checkAc_bal accessible to all methods, in order to perform calculations. I'm new on Java, and I'm trying to wrap my head on methods behaviors. Thanks so much.
...
import java.util.Scanner;
public class Main
{
public static void showMenu()
{
Scanner sc = new Scanner(System.in) ;
String input = null ;
do
{
input = showOptions(sc) ;
if(input != null)
{
switch(input.trim())
{
case "1" : deposit(sc) ;
break ;
case "2" : withdraw(sc);
break ;
case "3" : balanceInquiry() ;
break ;enter code here
case "4" : System.exit(0);
default : System.out.println("Wrong option entered. Exiting application") ;
System.exit(0);
}
}
}while(true) ;
}
public static String showOptions(Scanner sc)
{
System.out.println("********************Welcome to ATM Machine******************** ");
System.out.println("Enter Option");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance Inquiry");
System.out.println("4. Exit\n");
String input = sc.nextLine() ;
return input ;
}
public static void deposit (Scanner sc) {
int checkAc_bal = 0;
System.out.print("Enter amount to be deposited:");
int deposit;
Scanner s = new Scanner(System.in);
deposit = s.nextInt();
//int checkAc_bal = 0;
checkAc_bal = checkAc_bal + deposit;
System.out.println("Your Money has been successfully deposited");
System.out.println("Balance: " +checkAc_bal);
}
public static void withdraw (Scanner sc){
System.out.print("Enter money to be withdrawn:");
int withdraw;
Scanner s = new Scanner(System.in);
withdraw = s.nextInt();
if(withdraw<=checkAc_bal)
{
checkAc_bal = checkAc_bal - withdraw;
System.out.println("Please collect your money");
}
else
{
System.out.println("Insufficient Balance");
}
System.out.println("");
}
public static void balanceInquiry () {
System.out.println("Balance: " + checkAc_bal);
}
public static void main(String[] args) {
showMenu();
}
}
If you want your int to be accessible to other methods, you need to declare it in the scope of the whole class and not inside a method. Try declaring checkAc_bal in the Main class.
define it as a class member:
import java.util.Scanner;
public class Main
{
static int checkAc_bal = 0; //<------------------------add this
public static void showMenu()
{
Scanner sc = new Scanner(System.in) ;
String input = null ;
do
{
input = showOptions(sc) ;
if(input != null)
{
switch(input.trim())
{
case "1" : deposit(sc) ;
break ;
case "2" : withdraw(sc);
break ;
case "3" : balanceInquiry() ;
break ;enter code here
case "4" : System.exit(0);
default : System.out.println("Wrong option entered. Exiting application") ;
System.exit(0);
}
}
}while(true) ;
}
public static String showOptions(Scanner sc)
{
System.out.println("********************Welcome to ATM Machine******************** ");
System.out.println("Enter Option");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance Inquiry");
System.out.println("4. Exit\n");
String input = sc.nextLine() ;
return input ;
}
public static void deposit (Scanner sc) {
// int checkAc_bal = 0; <---------------- remove this
System.out.print("Enter amount to be deposited:");
int deposit;
Scanner s = new Scanner(System.in);
deposit = s.nextInt();
//int checkAc_bal = 0;
checkAc_bal = checkAc_bal + deposit;
System.out.println("Your Money has been successfully deposited");
System.out.println("Balance: " +checkAc_bal);
}
public static void withdraw (Scanner sc){
System.out.print("Enter money to be withdrawn:");
int withdraw;
Scanner s = new Scanner(System.in);
withdraw = s.nextInt();
if(withdraw<=checkAc_bal)
{
checkAc_bal = checkAc_bal - withdraw;
System.out.println("Please collect your money");
}
else
{
System.out.println("Insufficient Balance");
}
System.out.println("");
}
public static void balanceInquiry () {
System.out.println("Balance: " + checkAc_bal);
}
public static void main(String[] args) {
showMenu();
}
}
You have three queries, here are the answers :
Declare the variable globally to be accessible from all the methods.
Not to use switch case (U need to use if-else in that case)
How to pass parameters to methods in same class ?
I see you already did this in your code. You called other methods by parameters and received them as well.
Or frame your question well , as what exactly you need.
So here is the complete code :
import java.util.Scanner;
public class Main{
static int checkAc_bal = 0; // <---- declare on class scope
public static void showMenu() {
Scanner sc = new Scanner(System.in) ;
String input = null ;
do {
input = showOptions(sc) ;
if(input != null) {
// removed the switch-case and if-else used
if(input.trim().equals("1")) {deposit();}
else if(input.trim().equals("2")) {withdraw();}
else if(input.trim().equals("3")) {balanceInquiry();}
else if(input.trim().equals("4")) {System.exit(0);}
else {
System.out.println("Wrong option entered. Exiting application") ;
System.exit(0);
}
}
}while(true) ;
}
public static String showOptions(Scanner sc){
System.out.println("********************Welcome to ATM Machine******************** ");
System.out.println("Enter Option");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance Inquiry");
System.out.println("4. Exit\n");
String input = sc.nextLine() ;
return input ;
}
public static void deposit () {
System.out.print("Enter amount to be deposited:");
int deposit;
Scanner s = new Scanner(System.in);
deposit = s.nextInt();
checkAc_bal = checkAc_bal + deposit;
System.out.println("Your Money has been successfully deposited");
System.out.println("Balance: " +checkAc_bal);
}
public static void withdraw (){
System.out.print("Enter money to be withdrawn:");
int withdraw;
Scanner s = new Scanner(System.in);
withdraw = s.nextInt();
if(withdraw<=checkAc_bal) {
checkAc_bal = checkAc_bal - withdraw;
System.out.println("Please collect your money");
} else {
System.out.println("Insufficient Balance");
}
System.out.println("");
}
public static void balanceInquiry () {
System.out.println("Balance: " + checkAc_bal);
}
public static void main(String[] args) {
showMenu();
}
}
Output :
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
1
Input : 1
Enter amount to be deposited:100
Your Money has been successfully deposited
Balance: 100
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
1
Input : 1
Enter amount to be deposited:200
Your Money has been successfully deposited
Balance: 300
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
1
Input : 1
Enter amount to be deposited:200
Your Money has been successfully deposited
Balance: 500
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
3
Input : 3
Balance: 500
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
package oddsorevens;``
import java.util.Scanner;
import java.util.Random;
public class OddsOrEvens
{
public static void main(String[] args)
{
Scanner name= new Scanner (System.in); // getting input from user
System.out.print("Hi! What's your name: ");
String user = name.nextLine(); // getting user name
System.out.println("Hello: "+user);
System.out.println("Let's play OddsOrEvens");
System.out.println("Choose Odd or Even");
String s ="oddOrEven";
Scanner str = new Scanner(System.in); // getting new string from user
String s1 = str.next(); //storing odd or even here
o:
if (s1.equals("even")||(s1.startsWith("e")))
{
System.out.println("You choose even");
System.out.println("Computer choose odd");
}
else if (s1.equals("odd")||(s1.startsWith("o")))
{
System.out.println("You choose odd");
System.out.println("Computer choose even");
}
else
{
System.out.println("Entered wrong keyword");
}
System.out.print("How many fingers you want to put out: ");
Scanner num = new Scanner(System.in);
int n=num.nextInt();
Random rand = new Random();
int computer = rand.nextInt(6);
System.out.println("Computer choose "+ computer +" fingers");
int sum;
sum=n+computer;
System.out.println(sum);
if(sum%2==0)
{
System.out.println(sum+" is even");
}
else
{
System.out.println(sum+" is odd");
}
int u = s1.length();
if(u/2==0)
{
System.out.println("You won :)");
}
else
{``
System.out.println("You lose :(");
}
}
}
This is my first pgm in java. here if the user enter wrong keyword pgm should be break and based on the user input the output of the pgm will be win or lose. help please.
Whenever you want your application to stop, you have to explicitly tell that you want to exit. To do so you have write just piece of line of code and that is System.exit(0)
Here sample code to understand it better:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
if (s.next().equals("o")) {
System.out.println("game is still on");
} else {
System.out.println("game end!");
System.exit(0);
}
}
I am trying to get my program to exception handle for if the user inputs nothing so they will get an error message of "Error, enter a dollar amount greater than 0" or "Error, Enter a 1, 2 or 3". As of now, the program does nothing if the user just hits "enter" with no input....
import java.util.Scanner;
import java.util.*;
import java.text.DecimalFormat;
public class Candleline
{
public static void main(String[] args)
{
//initiate scanner
Scanner input = new Scanner(System.in);
System.out.println("\tCandleLine - Candles Online");
System.out.println(" ");
//declare variables and call methods
double candleCost = getCandleCost();
int shippingType = getShippingType();
double shippingCost = getShippingCost(candleCost, shippingType);
output(candleCost, shippingCost);
}
public static double getCandleCost()
{
//get candle cost and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
double candleCost = 0;
while(!done)
{
System.out.print("Enter the cost of the candle order: ");
try
{
inputCost = input.next();
candleCost = Double.parseDouble(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (candleCost <=0) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
}
return candleCost;
}
public static int getShippingType()
{
//get shipping type and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
int shippingCost = 0;
while(!done)
{
System.out.println(" ");
System.out.print("Enter the type of shipping: \n\t1) Priority(Overnight) \n\t2) Express (2 business days) \n\t3) Standard (3 to 7 business days) \nEnter type number: ");
try
{
inputCost = input.next();
shippingCost = Integer.parseInt(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (shippingCost <=0 || shippingCost >= 4) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println(" ");
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
}
return shippingCost;
}
public static double getShippingCost(double candleCost, int shippingType)
{
//calculate shipping costs
double shippingCost = 0;
if (shippingType == 1)
{
shippingCost = 16.95;
}
if (shippingType == 2)
{
shippingCost = 13.95;
}
if (shippingType == 3)
{
shippingCost = 7.95;
}
if (candleCost >= 100 && shippingType == 3)
{
shippingCost = 0;
}
return shippingCost;
}
public static void output(double fCandleCost, double fShippingCost)
{
//display the candle cost, shipping cost, and total
Scanner input = new Scanner(System.in);
DecimalFormat currency = new DecimalFormat("$#,###.00");
System.out.println("");
System.out.println("The candle cost of " + currency.format(fCandleCost) + " plus the shipping cost of " + currency.format(fShippingCost) + " equals " + currency.format(fCandleCost+fShippingCost));
}
}
Replace input.next();
with input.nextLine();
You can write a method that validates the input before proceeding. It can keep asking for inputs if user enters something that is not valid. E.g. below example demonstrates how to validate an integer input:
private static int getInput(){
System.out.print("Enter amount :");
Scanner scanner = new Scanner(System.in);
int amount;
while(true){
if(scanner.hasNextInt()){
amount = scanner.nextInt();
break;
}else{
System.out.println("Invalid amount, enter again.");
scanner.next();
}
}
scanner.close();
return amount;
}
I am just playing around with java and wanted to make a simple program where the user; me has to guess/type in the correct number until it's correct. What can I do so the program can keep running, printing out "Make another guess" until the user/me puts in the correct number. Maybe a boolean? I'm not sure. This is what I have so far.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
input.nextInt();
}
}
You might want to use a while loop to repeat some code:
while (value != myInt) {
System.out.println("Not yet! You entered: " + value + ". Make another guess");
value = input.nextInt();
}
System.out.println("You discovered me!");
This program would do the trick:
public static void main(String [] args){
int myInt = 2;
int value = 0;
Scanner input = new Scanner(System.in);
boolean guessCorrect = false;
while(!guessCorrect){
System.out.println("Not yet! You entered:" + value + " Make another guess");
value = input.nextInt();
if(value == myInt){
guessCorrect = true
}
}
System.out.println("You discover me!");
}
Simply introduce a loop.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
for(;;) {
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
break;
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
}
}
}
}