Reputation: 1375
Discovered WCF and consequently started exploring it. This is a C# console application. Code works fine except when I try to Withdraw. If I enter amount of wrong type it detects(catches), informs me of invalid input and sends me back to menu prompt. That's fine and dandy until I get to the part where I try to withdraw more dosh than I have(balance). Supposedly, I should've gotten message saying that I'm short on funds to withdraw so much. Instead I get this:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Where did I go wrong?
Main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace BankAccountClient
{
class Program
{
static void Main(string[] args)
{
BankAccountClient.ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
bool done = false;
do
{
Console.WriteLine("Select one of the following:");
Console.WriteLine("\t1 -- Withdraw");
Console.WriteLine("\t2 -- Deposit");
Console.WriteLine("\t3 -- Balance");
Console.Write("Enter Your selection (0 to exit): ");
string strSelection = Console.ReadLine();
int iSel;
try
{
iSel = int.Parse(strSelection);
}
catch (FormatException)
{
Console.WriteLine("\r\nWhat?\r\n");
continue;
}
Console.WriteLine("\nYou selected " + iSel + "\n");
switch (iSel)
{
case 0:
done = true;
break;
case 1:
int balance = client.Balance();
int amount;
//WCF Withdraw
Console.Write("How much would you like to withdraw?: ");
try
{
amount = int.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("\r\nInvalid input. Must be an integer\r\n");
continue;
}
if (amount > balance)
{
Console.WriteLine(String.Format("\r\nNot enough funds to withdraw ${0}\r\n"), amount);
continue;
}
else
client.Withdraw(amount);
Console.WriteLine(String.Format("\nCurrent balance is ${0}\n", client.Balance()));
break;
case 2:
//WCF Deposit
Console.WriteLine("Deposit();");
break;
case 3:
//WCF Balance
Console.WriteLine(String.Format("Current balance is ${0}", client.Balance()));
break;
default:
Console.WriteLine("You selected an invalid number: {0}\r\n", iSel);
continue;
}
Console.WriteLine();
} while (!done);
Console.WriteLine("\nGoodbye!");
}
}
}
WCF Service(short)
public class Service : IService
{
private static int balance;
public void Withdraw(int value)
{
balance -= value;
}
public void Deposit(int value)
{
balance += value;
}
public int Balance()
{
return balance;
}
}
Upvotes: 4
Views: 5650
Reputation: 1863
You have put a parenthesis in the wrong place. Change your output to this:
Console.WriteLine(String.Format("\r\nNot enough funds to withdraw {0}\r\n", amount));
Upvotes: 1
Reputation: 5825
You need to move amount into the String.Format method on this line
Console.WriteLine(String.Format("\r\nNot enough funds to withdraw ${0}\r\n"), amount);
So
Console.WriteLine(String.Format("\r\nNot enough funds to withdraw ${0}\r\n", amount));
Upvotes: 2