[英]passing arrays in c#
嗨,我正在從事成績計算。 我的問題是,如果字符串數組的長度比int數組長,則它會跳過最后兩個等級。 例如:
int[] unit = new int[] {1,-3,3,4};
string[] letter_grade = new string[] {"A", "B","B","W","D","F"};
但是,如果int數組的長度比字符串數組的長度長,則它無法正常工作,其拋出錯誤Index不在數組的范圍之內。
int[] unit = new int[] {1,-3,3,4,5,6,7};
string[] letter_grade = new string[] {"A", "B","B"};
所以我的問題是我如何使兩者都適用?
int length = unit.Length;
int no_units = length;
double totalGrade_Points = 0.0;
int totalno_units = 0;
totalGPA = 0;
for (int i = 0; i < unit.Length; i++)
{
entrygot = findGpaListentry(letter_grade[i]); //Index was outside the bounds of the array.
if (entrygot != null)
{
//some code calculation
}
}
您不能只檢查數組項是否為null,因為您將超出數組的范圍,並且在進行null檢查之前會獲得異常。
我會在每次迭代時檢查數組的長度...
for (int i = 0; i < unit.Length; i++)
{
if (currentArray.Length < i - 1) { break; }
// other code...
}
對於數組索引,必須很好地定義啟動和停止條件。 為了訪問兩個數組,它們必須相等或在某些有效條件下進行比較。 看看這個:
for(int i=0;i<unit.length;i++){
entrygot = findGpaListentry(letter_grade[i]);// only if letter_grade is valid under all values of i i.e unit.length
}
// either you have to check as if;
if(lenght_of_letter_grade < i-1)
//then access
entrygot = findGpaListentry(letter_grade[i]);
我認為在您的情況下,元素的數量永遠不會很大,因此性能不會成為問題。 因此,我認為您應該使用列表而不是數組。 使用數組時,每次邏輯更改或添加其他功能時,都必須進行插入檢查。
foreach
循環最適合您的場景。
foreach (string s in letter_grade)
{
entrygot = findGpaListentry(s);
if (entrygot != null)
{
//some code calculation
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.