Switch Statement

 [Previous Chapter]  [Previous Page]  [Contents]  [Next Page]  [Next Chapter]

TestBankAccount.java
switch (cmdletter) {
case 'b': // balance
   System.out.println("Current balance is " + account);
   break;

case 'd': // deposit
case 'w': // withdrawal
   amountAsDouble = RitIo.getDouble("Amount: ");
   amountAsInt = (int) amountAsDouble;
   amountAsDouble -= amountAsInt; // 123.456 becomes 0.456
   amountAsInt *= 100; // take int part as dollars (12300)
   amountAsDouble *= 100; // becomes 45.6
   amountAsInt += (int) amountAsDouble; // becomes 12345
   if (cmdletter == 'd') {
      account.deposit(amountAsInt);
   } else {
      account.withdraw(amountAsInt);
   }
   break;

*account is of type BankAccount which offers a toString method which supports a conversion to a String for the + operator.
 
*Note how the common part of reading an amount value for the commands ``deposit'' and ``withdrawal'' has been factorized out.
 

 [Previous Chapter]  [Previous Page]  [Contents]  [Next Page]  [Next Chapter]
Copyright © 2001, 2002 Andreas Borchert, converted to HTML on February 11, 2002