for (int i = 0; i <= 6; i++)
{
string[] doors = new string[6];
doors[i] = "#";
for (int j = 1; j <=i; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}
大家好我需要先打印#然后再打印两次,直到打印六遍为止。它说System.index.out.of.range。怎么来的?
答案 0 :(得分:2)
您应该尝试扩展数组,该数组限制为6个元素,但是在0到6之间尝试访问7个元素。
for (int i = 0; i <= 6; i++)
{
string[] doors = new string[7];
doors[i] = "#";
for (int j = 1; j <=i; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}
答案 1 :(得分:1)
因为它超出范围。
将其更改为此:
for (int i = 0; i <= 6; i++)
{
string[] doors = new string[6];
doors[i] = "#";
for (int j = 0; j <=i.length; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}
答案 2 :(得分:1)
无需使用2个循环。只是repeat that character
for (int i = 0; i <= 6; i++)
{
Console.Write(new String("#",i));
Console.WriteLine():
}
答案 3 :(得分:1)
如果
我需要先打印 #,然后两次#,直到我打印六遍。
您不需要任何 array -string[] doors = new string[6];
,只需循环:
for (int line = 1; line <= 6; ++line) {
for (int column = 1; column <= line; ++column) {
Console.Write('#');
}
Console.WriteLine();
}
如果您必须使用数组(即数组将在其他地方使用),请去除幻数:
// Create and fill the array
string[] doors = new string[6];
for (int i = 0; i < doors.Length; i++)
doors[i] = "#";
// Printing out the array in the desired view
for (int i = 0; i < doors.Length; i++) {
for (int j = 0; j < i; j++) {
Console.Write(doors[j]);
}
Console.Writeline();
}
请注意,数组是基于从零开始的(具有6
个项目的数组具有0..5
个索引)