class Program
{
int[] arrayOne = new int[3];
int[] arrayTwo = new int[5];
int[] arrayThree = new int[7];
int sumOne = 0;
int sumTwo = 0;
int sumThree = 0;
static void Main()
{
//call method to generate numbers
generateRandomNumbers();
//call method to get sums of arrays
sumOne = getSum(arrayOne);
sumTwo = getSum(arrayTwo);
sumThree = getSum(arrayThree);
//call method to show numbers in each array and their sum
showNumbers(arrayOne);
showNumbers(arrayTwo);
showNumbers(arrayThree);
ReadKey();
}
private static void generateRandomNumbers()
{
Random random = new Random();
//load in values for arrayOne
for (int i = 0; i < arrayOne.Length; i++)
arrayOne[i] = random.Next(1, 99);
//arrayTwo
for (int j = 0; j < arrayTwo.Length; j++)
arrayTwo[j] = random.Next(1, 99);
//arrayThree
for (int k = 0; k < arrayThree.Length; k++)
arrayThree[k] = random.Next(1, 99);
}
private static int getSum(int[] array)
{
int total = 0;
for (int x = 0; x < array.Length; x++)
total += array[x];
return total;
}
private static void showNumbers(int[] array)
{
for (int m = 0; m < array.Length; m++)
Write("{0, 5}", array[m]);
switch (array.Length)
{
case 3:
Write(" = {0}", sumOne);
break;
case 5:
Write(" = {0}", sumTwo);
break;
case 7:
Write(" = {0}", sumThree);
break;
}
WriteLine();
}
}
基本上,错误发生在我使用arrayOne,arrayTwo,arrayThree和sumOne,sumTwo,sumThree的每个地方。从Main和generateRandomNumbers方法中删除'static'会删除所有错误,但是当然没有静态Main方法就无法编译。
在我的C#课程中,我们目前正在学习方法和数组,该程序的目标是将随机数放入三个数组中,然后显示每个数字和数组的总和。
我已经四处寻找,答案主要是“创建一个实例”,但我不知道如何去做。任何帮助将不胜感激!
答案 0 :(得分:3)
当你把所有内容都填入Program
时,通常最简单的方法就是让所有东西都是静态的,因为Main
需要是静态的。因此,一种选择是使您的字段保持静态:
static int[] arrayOne = new int[3];
static int[] arrayTwo = new int[5];
static int[] arrayThree = new int[7];
static int sumOne = 0;
static int sumTwo = 0;
static int sumThree = 0;
另一个选项是使用以下语法使所有内容非静态地创建Program
的实例:
var program = new Program();
然后引用该实例的属性和方法:
//call method to generate numbers
program.generateRandomNumbers();
//call method to get sums of arrays
program.sumOne = program.getSum(arrayOne);
program.sumTwo = program.getSum(arrayTwo);
program.sumThree = program.getSum(arrayThree);
正如您所看到的,除非您需要为每个实例提供不同的属性,否则将所有内容保持为静态更容易。