I am having trouble with a method that is called within main and is contained in the same class. The method is outputting a string value and my problem is trying to include references to arrays within the string message. I am getting the message
Only assignment, call, increment, decrement, and new object expressions can be used as a statement"
Along with invalid expression in regards to the comma and a whole bunch of ; expected all in regards to the following line:
searchResult = "Account #" + accountsarr[i] + " has a balance of {0:c}" + " for customer " + namesarr[i], balancesarr[i]";
all within the following method:
public static string searchAccounts(ref int AccountNumber, int[] accountsarr, double[] balancesarr, string[] namesarr)
{
bool isValidAccount = false;
int i = 0;
while (i < accountsarr.Length && AccountNumber != accountsarr[i])
{
++i;
}
if (i != accountsarr.Length)
{
isValidAccount = true;
}
string searchResult;
if (isValidAccount)
{
searchResult = "Account #" + accountsarr[i] + " has a balance of {0:c}" + " for customer " + namesarr[i], balancesarr[i]";
}
else
searchResult = "You entered an invalid account";
return searchResult;
}
So how do you return a string from a method that has references to array positions within the text that should be the string?
" + namesarr[i], balancesarr[i]";
Paul Bellora 2012-04-04 04:47
You should use string.Format like this:
searchResult = string
.Format("Account # {0} has a balance of {1:c} for customer {2}",
accountsarr[i], balancesarr[i], namesarr[i]);
The error you get is syntactic, you have a comma instead of a +
and an extra "
Just you know why your code isn't compiling:
searchResult = "Account #" + accountsarr[i] + " has a balance of {0:c}"
+ " for customer " + namesarr[i], balancesarr[i]"; << this is an extra "
//^ you cannot put a comma here
searchAccounts(int,int,double,string)
. Your function expects arrays but you are passing single elements of the array into the function - gideon 2012-04-04 05:50
You can simply do the following:
searchResult = "Account #" + accountsarr[i] + " has a balance of "+String.Format("{0:c}",balancesarr[i]) + " for customer " + namesarr[i];
String.Format
- John Saunders 2012-04-04 04:45