2015-10-01 77 views
1

我正在創建一個正在創建一個ASCII圖像的程序。基於asterix輸入,它會產生不同的結果。要開始我正在做一個基本的概述,但是我有一個問題,當我檢查最後一個循環迭代時,我不能添加一些東西。檢查下一個循環迭代數據,除非循環結束c#

方法代碼:

 private List<string> DrawOutline(List<string> inputLines) 
    { 
     List<string> output = new List<string>(); 
     int door = r.Next(0, inputLines.Last().Length); 
     for (int li = 0; li < inputLines.Count; li++) 
     { 
      char[] curLine = inputLines[li].ToCharArray(); 
      string outputLine1 = string.Empty; 
      string outputLine2 = string.Empty; 
      for (int i = 0; i < curLine.Length -1; i++) 
      { 
       Console.WriteLine(curLine[i]); 
       if (curLine[i] == '*') 
       { 
        outputLine1 += "+---"; 
        outputLine2 += "| "; 
       } 
       else 
       { 
        outputLine1 += " "; 
        outputLine2 += " "; 
       } 
       if(li < curLine.Length - 1) 
       { 
        if (curLine[i] == '*' && curLine[i + 1] != '*') 
        { 
         outputLine1 += "+"; 
         outputLine2 += "|"; 
        } 
       } 
      } 
      output.Add(outputLine1); 
      output.Add(outputLine2); 
     } 
     return output; 
    } 

當我運行它,它工作正常但不會添加 '+' 和 '|'到outputLines的最後一行。這是因爲該行:

if(li < curLine.Length -1) 

但是沒有-1,因爲我使用的[I + 1]來決定的東西它會拋出異常。有沒有辦法只檢查它是否不會拋出異常?

回答

0

您可以使用OR(||)語句來檢查數組的末尾是否已經到達。如果OR語句的第一條語句返回true,則不檢查第二條語句。這叫做short-circuiting。在這種情況下不應該拋出錯誤。

private List<string> DrawOutline(List<string> inputLines) 
{ 
    List<string> output = new List<string>(); 
    int door = r.Next(0, inputLines.Last().Length); 
    for (int li = 0; li < inputLines.Count; li++) 
    { 
     char[] curLine = inputLines[li].ToCharArray(); 
     string outputLine1 = string.Empty; 
     string outputLine2 = string.Empty; 
     for (int i = 0; i < curLine.Length -1; i++) 
     { 
      Console.WriteLine(curLine[i]); 
      if (curLine[i] == '*') 
      { 
       outputLine1 += "+---"; 
       outputLine2 += "| "; 
      } 
      else 
      { 
       outputLine1 += " "; 
       outputLine2 += " "; 
      } 

      if (curLine[i] == '*' && (curLine.Length == i+1 || curLine[i + 1] != '*')) 
      { 
       outputLine1 += "+"; 
       outputLine2 += "|"; 
      } 

     } 
     output.Add(outputLine1); 
     output.Add(outputLine2); 
    } 
    return output; 
} 
0

變化if (li < curLine.Length - 1)if (i < curLine.Length - 1)