c#中解析输入字符串为整型值时出错

本文关键字:整型 出错 字符串 输入 | 更新日期: 2023-09-27 18:08:27

第一个if作品很棒

第二个if抛出异常

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a number and click enter, continue doing this process ");
        Console.WriteLine("When you finish, just click enter without giving any input");
        int i = 0;
        int[] numbersArray;
        List<int> numbersList = new List<int>();
        while (true)
        {
            String numInput = Console.ReadLine();
            numbersList.Add(Int32.Parse(numInput));
            numbersArray = numbersList.ToArray();
            if (i >= 1)
            {
                if (numbersArray[i] < numbersArray[i - 1])
                {
                    Console.WriteLine("Your series is not going up!");
                    break;
                    Environment.Exit(0);
                }
                if (numbersArray[i] > numbersArray[i - 1])
                {
                    if (numInput == "") { 
                        break;
                    }
                }
            }
            i++;
        }
            Console.WriteLine("You entered this series: ");
            for (int j = 0; j < numbersArray.Length; j++)
            { 
                Console.WriteLine(" " + numbersArray[j]);
            }
            Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);

    }
}

c#中解析输入字符串为整型值时出错

不能解析没有数字的字符串,如numInput =" "

编辑:试试这个代码:

 static void Main(string[] args)
    {
        Console.WriteLine("Enter a number and click enter, continue doing this process ");
        Console.WriteLine("When you finish, just click enter without giving any input");
        int i = 0;
        int[] numbersArray = new []{1};
        List<int> numbersList = new List<int>();
        while (true)
        {
            String numInput = Console.ReadLine();
            if (numInput == null || !numInput.All(char.IsDigit)) continue;
            if (numInput != "")
            {
                numbersList.Add(Int32.Parse(numInput));
                numbersArray = numbersList.ToArray();
                if (i >= 1)
                {
                    if (numbersArray[i] < numbersArray[i - 1])
                    {
                        Console.WriteLine("Your series is not going up!");
                        break;
                        Environment.Exit(0); // <-- Code is unreachable!
                    }
                }
            i++;
            }
            else if(i >= 1)
            {
                break;
            }
        }
        Console.WriteLine("You entered this series: ");
        foreach (int t in numbersArray)
        {
            Console.WriteLine(" " + t);
        }
        Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
        Console.ReadLine();
    }

我猜您正在尝试查看一个不存在的索引。

不确定你的语言,但我猜numbersArray[0]是第一个索引和numbersArray[1]是第二个。所以当你输入第一个数字时你试着去看numbersArray[1]它不存在