为什么我的数组中总是有0,而它应该什么都没有——C#

  • 本文关键字:数组 c# arrays
  • 更新时间 :
  • 英文 :


我正在为学校做一些事情,只是一个基本的分数计算器。我知道这不是最漂亮的代码,但它是有效的,这也是课程一开始关注的重点。

我唯一的问题是,每当我点击"显示"时,它都会打印出20秒。20是阵列的长度。其他一切都在起作用。它将我输入的数字添加到数组中,并替换0。但我不希望它有0,除非我特别键入它们。

感谢您的帮助。

完整代码:

// Creates the list that displays the score
List<string> scoreList = new List<string>();
// Array to store up to 20 scores
int[] scoreArray = new int[20];
// class level variable to store current open slot in the array
int openSlot = 0;
public Form1()
{
InitializeComponent();
}
// Initializes variables that hold our math total and count of numbers entered
int total = 0;
int count = 0;
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void btnAdd_Click(object sender, System.EventArgs e)
{
if (openSlot <= scoreArray.GetUpperBound(0))
{
try
{
// Basic math for conversion of entered number and calculating total numbers entered
// and the averages of those numbers
int score = Convert.ToInt32(txtScore.Text);
total += score;
count += 1;
int average = total / count;
txtScoreTotal.Text = total.ToString();
txtScoreCount.Text = count.ToString();
txtAverage.Text = average.ToString();
txtScore.Focus();
}
catch(System.FormatException) // Makes sure that the user enters valid character into box
{
MessageBox.Show("Please enter valid number into box");
return;
}
// Adds the most recent entered number to the Score List
scoreList.Add(txtScore.Text);
}
// if statement to make sure that there is still room in the array to store the
// new entry
if (openSlot > scoreArray.GetUpperBound(0)) // GetUpperBound(0) returns the index of the last element in the first dimension
{
MessageBox.Show("The array is full! The most recent number was not added.");
txtScore.SelectAll();
txtScore.Focus();
return;
}
// Assigns a variable as an integer from the score text box
// to allow us to numerically sort the numbers in the scoreArray
int scoreParse = Int32.Parse(txtScore.Text);
// move the most recent number to the current open slot in the score array
scoreArray[openSlot] = scoreParse;
// add 1 to openSlot
openSlot += 1;
}
private void btnClear_Click(object sender, EventArgs e)
{
// Clears all input fields and resets variables to 0
openSlot = 0;
total = 0;
count = 0;
txtScore.Text = "";
txtScoreTotal.Text = "";
txtScoreCount.Text = "";
txtAverage.Text = "";
txtScore.Focus();
// Clears the array and list
int[] clearScoreArray = new int[20];
scoreArray = clearScoreArray;
List<string> clearScoreList = new List<string>();
scoreList = clearScoreList;
}
private void btnDisplay_Click(object sender, EventArgs e)
{
// If array has no stored values, display a MessageBox that informs user
if (scoreArray == null || scoreArray.Length == 0)
{
MessageBox.Show("There are no numbers to display");
return;
}
//move focus to the code textbox
txtScore.Focus();
// Creates a blank string variable named scr to input the scores into
// for the MessageBox
string scr = "";
foreach (var scoreAdded in scoreArray)
{
// Adds variable scr as the string to display 
scr += scoreAdded + "n";
}
// Sorts the array from lowest to highest number
Array.Sort(scoreArray);
// Displays a message box with the scores that were added
MessageBox.Show(scr);
}
}

当您声明一定数量的数组(在您的位置是20)时,它们会得到某种值,通常是0。当您使用myArrayHere.length时,请记住这一点,因为它将检查有多少个数组已声明(int[]array)和初始化(…=new array[]),而不是有多少个已修改(给定值)。

最好的解决方案,IMO是创建一个函数,它可以知道你需要一个数组中有多少元素,或者你正在使用其中的多少元素(只要有一个函数就可以了,它返回使用的变量的数量,用循环检查它,然后在以后修改它……但这是解决这个问题的一种方法,有比我指出的更好的修复方法,但正如我所看到的,你对C#(prob。)用ok'ish代码解决你的问题是好的,因为你的第一个项目应该是为了学习,以后你可以改进它,如果你想成为一名专业人士,可以参加一些关于如何改进你的代码的编程课程)。

祝你好运!-Normantas

如果不希望零作为默认值,可以使用nullable。

int?[]array=new int?[20] ;

欢迎来到SO!

当一个对象最初被声明时,会有一个默认的初始化值。在这种情况下,0是C#中int的默认值。如果有支持构造函数,则通常可以在对象初始化时更改默认值。

当声明int[] scoreArray = new int[20];时,所有20个变量都被赋值为0。这是因为C#不允许未初始化的变量。

此链接显示C#的所有默认初始化值。

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table

最新更新