我有一个小程序可以更改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);
}
}
P.S。你能否告诉我如何使这段代码变得更优雅?
答案 0 :(得分:0)
当读取单个字符时,建议使用Console.ReadKey()。KeyChar。我已修改您的代码以处理异常:
static void addLetters(char[] messageOne, char[] messageTwo)
{
char Mnumber;
char letter;
string pos;
int position;
try
{
do
{
Console.Write("- Message #: ");
Mnumber = Console.ReadKey().KeyChar;
Console.WriteLine();
}
while (Mnumber != '1' && Mnumber != '2');
Console.Write("\nLetter: ");
letter = Console.ReadKey().KeyChar;
Console.Write("\nPosition: ");
pos = Console.ReadLine();
position = Int32.Parse(pos);
if (Mnumber == '1')
messageOne[position - 1] = letter;
else
messageTwo[position - 1] = letter;
}
catch (FormatException)
{
Console.WriteLine("Invalid input format, position must be an integer");
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Position out of array bounds");
}
finally
{
Console.Read();
}
}
答案 1 :(得分:0)
为两个消息尝试单个函数,并将TryParse()
字符串转换为整数转换
static char ReadChar(string prompt)
{
// Screen Prompt
Console.Write(prompt);
// Read a Character
return Console.ReadKey(false).KeyChar;
}
static int ReadNumber(string prompt)
{
// Screen Prompt
Console.Write(prompt);
int result=-1;
// Reads a number and onverts it into an integer
int.TryParse(Console.ReadLine(), out result);
return result;
}
// Caution, this modifies the contents of `messages`
static void addLetters(params char[][] messages)
{
// Read message index (first=1, second=2, etc)
int Mnumber=ReadNumber("- Message #: ");
// Read letter
char letter=ReadChar("Letter: ");
// Read placement position
int position=ReadNumber("\nPosition: ");
// Get the right message
char[] current_message=messages[Mnumber-1];
// Assigns a letter to the message
current_message[position]=letter;
}
static void Main(string[] args)
{
int n=50; //Store the size instead of hard coding it all over your code
char[] array1=new char[n];
char[] array2=new char[n];
for (int i=0; i<n; i++)
{
array1[i]='*';
array2[i]='*';
}
addLetters(array1, array2);
}