我有这段代码,当我运行它时,错误在new Program(int.Parse(args[0]));
,异常是
索引超出了数组的范围
我的代码:
using System;
using System.Threading.Tasks;
using System.Linq;
namespace MagicSquares
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
new Program(int.Parse(args[0]));
}
private int n;
private int constant;
private int[,] solution;
public Program(int n)
{
this.n = n;
int nSquared = n * n;
int sumAllNumbs = nSquared * (nSquared + 1) / 2;
constant = sumAllNumbs / n;
int threads = Environment.ProcessorCount;
Parallel.For(0, threads, (i) =>
{
Random rnd = new Random();
int[] numbers = Enumerable.Range(1, nSquared).ToArray();
int[,] square = new int[n, n];
do
{
RandomizeNumbers(rnd, numbers);
FillSquare(square, numbers);
if (IsMagicSquare(square))
solution = square;
} while (solution == null);
});
PrintSquare(solution);
}
private void RandomizeNumbers(Random rnd, int[] numbers)
{
for (int i = numbers.Length - 1; i >= 0; i--)
{
int index = rnd.Next(numbers.Length);
int temp = numbers[i];
numbers[i] = numbers[index];
numbers[index] = temp;
}
}
private void FillSquare(int[,] square, int[] numbers)
{
int index = 0;
for (int y = 0; y < n; y++)
for (int x = 0; x < n; x++)
{
square[y, x] = numbers[index];
index++;
}
}
private bool IsMagicSquare(int[,] square)
{
//Check horizontal
for (int y = 0; y < n; y++)
{
int sum = 0;
for (int x = 0; x < n; x++)
sum += square[y, x];
if (sum != constant)
return false;
}
//Check vertical
for (int x = 0; x < n; x++)
{
int sum = 0;
for (int y = 0; y < n; y++)
sum += square[y, x];
if (sum != constant)
return false;
}
return true;
}
private void PrintSquare(int[,] square)
{
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
Console.Write(square[y, x] + " ");
Console.WriteLine();
}
}
}
}
答案 0 :(得分:2)
问题:您的错误明确告诉您正在访问args [0]索引零元素,但args数组没有元素。
解决方案:您需要将命令行参数传递给您的程序,并且还需要确保在访问数组之前有元素以避免运行时异常。
试试这个:
if(args.Length > 0)
new Program(int.Parse(args[0]));
您可以通过以下方式之一传递命令行参数:
方法1:如果从Visual Studio运行应用程序,可以通过以下步骤传递命令行参数:
1.转到项目Properties
2.选择Debug
标签
3.在CommanLine Arguments
文本框
方法2:如果从命令行运行应用程序,可以通过以下命令传递命令行参数:
c:\MyPrograms\>MyApplication.exe 23
答案 1 :(得分:0)
尝试检查args是否为空if(args.Length>0)
class Program
{
static void Main(string[] args)
{
if(args.Length>0)
new Program(int.Parse(args[0]));
}
答案 2 :(得分:0)
args
参数用于命令行参数。您可以从命令提示符yourexe <some integer>
运行程序,您将看到没有异常。或者,从visual studio中的项目属性中,您还可以设置在调试时提供的命令行参数。