Swict case and Do-while loop control structures combined.

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package switchdowhile;

import java.util.Scanner;

/**
*
* @author derdus
*/
public class SwitchDoWhile {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//declare your variables here
String reply;
do{
String response;
double initial_balance = 10000;
//we assume that deposit is zero
double deposit = 0;
// we assume withdrawal is zero also
double withdrawal = 0;
/*We need to declare the scanner object
to allow a user to input something
*/
Scanner scan =  new Scanner(System.in);
Scanner user_deposit = new Scanner(System.in);
Scanner user_withdrawa = new Scanner(System.in);
/*we have our variable now; we start
the outputs
*/
System.out.println("Reply with");
System.out.println("B: to check balance");
System.out.println("W: to Withdraw");
System.out.println("D: to Deposit");
/*Now use the scanner object to receive user
input- response
*/
response = scan.nextLine().trim();
/*We have used the trim() method to do remove any
leading or trailing space.
We will now use the response in for switch execution
paths.
*/
switch (response){
/*Note that switch has opening and closing
curl brackets. so our code goes in between
the brackets
*/
case "B":
System.out.println("Your balance is: " + initial_balance);
break;
case "W":
System.out.println("Enter amount to withdraw:");
withdrawal = user_withdrawa.nextDouble();
if(withdrawal>initial_balance){
//No sufficint funds
System.out.println("No sufficint funds!");
}else{
/*allow the user to withdraw, then compute
new balance
*/
System.out.println("You withdrew " + withdrawal);
System.out.println("Your new balance is " + (initial_balance-withdrawal));
}
break;
case "D":
System.out.println("Enter amount to deposit:");
deposit = user_deposit.nextDouble();
System.out.println("You have deposited" + deposit);
System.out.println("Your new balance is " + (initial_balance + deposit));
default:
/*This path executed when none of the inputs match
the cases. e.g. when a user enters a letter other
than B,W or D.
*/
System.out.println("Invalid entry");
}
System.out.println("Do you want to perfom another transaction. Reply (Y/n)");
Scanner user_reply = new Scanner(System.in);

reply = user_reply.nextLine();
}while(reply.equalsIgnoreCase("y"));

}

}
3 Comments

Add a Comment

Your email address will not be published. Required fields are marked *