2020年12月22日星期二

C# - Error "System.ArgumentOutOfRangeException: Length cannot be less than zero." but no error when placed into WriteLine as parameter? [duplicate]

Background:
Hi, I am currently learning C# and doing some practices at HackerRank. So I've come across a staircase problem which I should code to receive an integer input, then output the staircase 'diagram' using spaces and hashes.

Challenge faced:
The codes below give me a Runtime Error that says " System.ArgumentOutOfRangeException: Length cannot be less than zero. "

    // Complete the staircase function below.      static void staircase(int n) {                    // Find number of spaces needed           string space = "";              for (int i = 1; i < n; i++) {              space += " ";          }            string hash = "#";          for (int j = 0; j < n; j++) {                           space = space.Substring(0, space.Length - j);              Console.WriteLine(space + hash);                        hash += "#";                }        }  

However, when I change the code in the second for loop from

            space = space.Substring(0, space.Length - j);              Console.WriteLine(space + hash);    

to Console.WriteLine(space.Substring(0, space.Length - j) + hash);

It then runs successfully, I see no difference and am confused why does it work?

https://stackoverflow.com/questions/65418567/c-sharp-error-system-argumentoutofrangeexception-length-cannot-be-less-than December 23, 2020 at 11:17AM

没有评论:

发表评论