我有一个改变char数组值的小程序。但首先你需要告诉程序哪个数组你想改变一个值;并将新值及其位置写入该相同阵列位置。程序跳过代码行
但是,当我输入数组编号时,程序将跳过允许输入新值及其位置的代码行。然后程序在最后抛出一个FormatException。
下面的代码:
static void addLetters(char[] messageOne, char[] messageTwo)
{
char Mnumber;
char letter;
string pos;
int position;
Console.Write("- Message #: ");
Mnumber = (char)Console.Read();
if (Mnumber == '1')
{
Console.Write("Letter: ");
letter = (char)Console.Read();
Console.Write("\nPosition: ");
pos = Console.ReadLine();
position = Int32.Parse(pos);
messageOne[position - 1] = letter;
}
if (Mnumber == '2')
{
Console.Write("Letter: ");
letter = (char)Console.Read();
Console.Write("\nPosition: ");
pos = Console.ReadLine();
position = Int32.Parse(pos);
messageTwo[position - 1] = letter;
}
}
static void Main(string[] args)
{
char[] array1 = new char[50];
char[] array2 = new char[50];
for (int i = 0; i < 50; i++)
{
array1[i] = '*';
array2[i] = '*';
}
addLetters(array1, array2);
}
}
附:你能告诉我如何让这段代码更“优雅”吗?
告诉我们这行给了一个错误。 – Rob
'position = Int32.Parse(pos);'line给出错误 – Alex
您可能想使用'TryParse'而不是'Parse'。 – jhmt