C#如何在将用户存储在整数数组中之前检查用户是否输入了字符串或整数

时间:2016-03-17 14:02:31

标签: c# arrays

我更新了我的程序。这是它的作用。
1。用户输入限制(必须是数字)
2。如果是整数,则存储在整数中。否则,再问一遍。 (已用if-else处理)
3。用户输入值(必须是数字)
4。如果是整数,则存储在整数数组中。否则,再问一遍。 (这是问题)

Console.Write("\n  Enter limit on how many number(s): ");
string limit = Console.ReadLine();

int value;
if (int.TryParse(limit, out value))
{
    int size = int.Parse(limit);
    int[] a = new int[size];

    for (int i = 0; i < size; i++)
    {
        //I need this part to filter first the input of user
        Console.Write("  Value: ");
        //If integer, I need it to be stored in the array
        a[i] = Convert.ToInt32(Console.ReadLine());

        /*string val = Console.ReadLine();
        int detect;
        if(!int.TryParse(Console.ReadLine(), out detect))
        {
            break;
        }
        else
        {

        }*/
    }
    int len = a.Length;
    Program pj = new Program();
    pj.programBExtension(a, len);
}
else
{
    Console.Clear();
    Console.WriteLine("\n  You have entered an invalid value. You will be asked again to enter the limit.");
    goto progB;
}

2 个答案:

答案 0 :(得分:1)

在Loop中使用相同的棘手TryParse;

for (int i = 0; i < size; i++)
{
    if(!int.TryParse(Console.ReadLine(),out a[i])
    {
        break; // This is wrong input handle this
    }
}

答案 1 :(得分:0)

您已经过滤掉了无法转换为整数的字符串,因此只需使用该值&#39;检测&#39;:

        string b = Console.ReadLine();
        int detect;
        if (int.TryParse(b, out detect)) <-- Will filter out strings here

            for (int i = 0; i < size; i++)
            {
                a[i] = detect;
            }
            int len = a.Length;
            Program pj = new Program();
            pj.programBExtension(a, len);