大家好,我是編碼新手,也是陣列新手,我想知道如何讓這個代碼在陣列中沒有更多名稱時停止,并且停止在名稱之前始終說出數字 10。以及上面一個數字顯示名稱的位置,不僅僅是從 0 開始,而是從 1 開始。
這是我到目前為止所擁有的。
string[] list = new string[10];
int pos = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string StudentName;
StudentName = textBox1.Text;
list[pos] = StudentName;
pos ;
textBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(list.GetLength(0).ToString());
string message;
for (int i = 0; i < lista.GetLength(0); i )
{
message = "";
message = "The student" " " list[i] " has the position " i ;
MessageBox.Show(message);
}
}
uj5u.com熱心網友回復:
使用動態陣列,又名List<T>
List<string> list = new List<string>();
無需手動跟蹤位置,只需將專案添加到末尾:
list.Add(StudentName);
您可以使用 .Count 檢查串列中當前專案的數量。
for (int i = 0; i < list.Count; i ) {...}
但是您也可以使用 foreach 回圈遍歷串列中的所有專案,但是這樣您不會自動獲得位置。
foreach(var item in list){...}
uj5u.com熱心網友回復:
為了完整起見,另一種方法是過濾掉空條目。Linq 特別適合使用以下 Enumerables:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/ https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable。在哪里?view=net-6.0
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string[] list = new string[10];
list[0] = "test1";
list[1] = "test2";
for (var index = 0; index < list.Length; index )
{
var s = list[index];
Console.WriteLine($"[{index}] {s}");
}
// Filter out null, an empty string or only whitespace characters from the array
list = list
.Where(c => !string.IsNullOrWhiteSpace(c))
.ToArray();
Console.WriteLine("==========================");
for (var index = 0; index < list.Length; index )
{
var s = list[index];
Console.WriteLine($"[{index}] {s}");
}
}
}
https://dotnetfiddle.net/g7e0Nm
uj5u.com熱心網友回復:
首先,您可以使用指定陣列的最大容量const
const int arrayCapacity = 10;
string[] list = new string[arrayCapacity];
int pos = 0;
然后,如果陣列已滿,根據您的最大容量和/或文本框是否為空,您應該添加一些驗證。
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Textbox was empty");
return;
}
if (pos > arrayCapacity - 1)
{
MessageBox.Show("Array is full");
textBox1.Clear();
return;
}
list[pos] = textBox1.Text;
pos ;
textBox1.Clear();
}
最后一步是創建一個新陣列,以防萬一您的學生人數少于初始陣列的容量
private void button2_Click(object sender, EventArgs e)
{
var arr = list.Where(x => !string.IsNullOrEmpty(x)).ToArray();
for (int i = 0; i < arr.Length; i )
{
string message = "The student" " " arr[i] " has the position " (i 1);
MessageBox.Show(message);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491591.html
上一篇:C Unix和Windows支持
