문제
배열을 사용하여 운동을해야합니다. 사용자는 3 개의 입력 (매번 항목에 대한 정보)을 입력해야하며 입력은 배열에 삽입됩니다. 그런 다음 배열을 표시해야합니다.
그러나 정보를 변경하지 않고 배열 길이를 늘리는 데 어려움을 겪고 있습니다. 그리고 사용자가 다른 입력 세트를 입력하도록하려면 어떻게해야합니까? 이것이 내가 지금까지 가지고있는 것입니다.
public string stockNum;
public string itemName;
public string price;
string[] items = new string[3];
public string [] addItem(string[] items)
{
System.Console.WriteLine("Please Sir Enter the stock number");
stockNum = Console.ReadLine();
items.SetValue(stockNum, 0);
System.Console.WriteLine("Please Sir Enter the price");
price = Console.ReadLine();
items.SetValue(price, 1);
System.Console.WriteLine("Please Sir Enter the item name");
itemName = Console.ReadLine();
items.SetValue(itemName, 2);
Array.Sort(items);
return items;
}
public void ShowItem()
{
addItem(items);
Console.WriteLine("The stock Number is " + items[0]);
Console.WriteLine("The Item name is " + items[2]);
Console.WriteLine("The price " + items[1]);
}
static void Main(string[] args)
{
DepartmentStore depart = new DepartmentStore();
string[] ar = new string[3];
// depart.addItem(ar);
depart.ShowItem();
}
그래서 내 질문은 다음과 같습니다.
사용자가 하나 이상의 배치 입력을 입력 할 수 있도록하려면 어떻게해야합니까? 예를 들어, 사용자가 항목에 대한 정보 (소켓 번호, 가격 및 이름)에 대한 정보를 처음 입력 할 때 사용자가 다른 항목에 대한 자세한 정보를 입력 할 수 있어야합니까?
배열에 하나 이상의 항목이 있다는 가정에 따라 배열의 각 항목의 소켓 번호, 가격 및 이름을 어떻게 표시 할 수 있습니까?
해결책
.NET (c#)에서 배열을 재현 할 수 없습니다. JavaScript와 같지 않거나 PHP는 어레이가 매우 유연하게 만들어졌으며 임의의 요소로 확장 될 수 있습니다.
정의 당 기본 정적 배열에는 수정 크기가 있으므로 인덱스를 사용하여 내부의 요소를 참조 할 수 있습니다. ( http://en.wikipedia.org/wiki/array_data_structure#array_resizing ) 그러나 거기에서 동적 배열에 대해 읽을 수 있습니다. C#에서는 System.Collections.arrayList-Object입니다. ( http://en.wikipedia.org/wiki/dynamic_array )
따라서 필요한 것은 Arraylist 정의 또는 일반 목록 또는 일반 목록입니다. (System.Collections.generic.list)
string[] items = new string[3] { "input1", "input2", "input3" };
string[] moreItems = new string[10] { "input4", "input5" };
// array to list
List<string> itemsList = items.ToList<string>();
itemsList.Add("newItem");
// or merge an other array to the list
itemsList.AddRange(moreItems);
// list to array
string[] newArray = itemsList.ToArray();
다른 팁
.NET 프레임 워크 3.5로 시작하여 1 차원 배열을 사용할 수 있습니다. Array.Resize<T>
방법:
int[] myArray = { 1, 2, 3 };
Array.Resize(ref myArray, 5);
MSDN 링크입니다 여기.
나는 당신이 문제를 잘못하고있을 것 같아요 ...
세 항목 (주식 번호, 가격 및 이름)이 더 큰 개체의 일부라고 생각하십시오. 지금은 우리는 그것을 부를 수 있습니다 item
. 우리는 여러 가지를 저장하고 싶습니다 item
목록 또는 배열에있는 s. 다음과 같은 객체 지향적 접근법을 고려하십시오.
class Widget
{
public int StockNum;
public int Price;
public string Name;
Widget(stockNum, price, name)
{
this.StockNum= stockNum;
this.Price = price;
this.Name = name;
}
}
이제 이러한 객체의 목록을 인스턴스화 할 수 있습니다.
List<Widget> items = new List<Widget>();
그리고 그들에게 항목을 추가하십시오.
for (int i = 0; i < 5; i++)
{
//Get input from user
System.Console.WriteLine("Please Sir Enter the stock number");
stockNum= Convert.ToInt32(Console.ReadLine()); //This isn't very safe...
System.Console.WriteLine("Please Sir Enter the price");
price = Convert.ToInt32(Console.ReadLine()); //This isn't very safe...
System.Console.WriteLine("Please Sir Enter the item name");
name = Console.ReadLine();
//Then add it to a new object
Widget item = new Widget(stockNum, price, name);
//And add this item to a list
items.Add(item);
}
과제가 다른 컬렉션 클래스가 아닌 배열을 사용해야한다고 가정하면 어려운 방법으로해야 할 일을해야합니다.
배열은 불변입니다. 즉, 만들어진 후에는 변경할 수 없습니다. 배열의 크기는 아니지만 내용을 변경할 수 있습니다. 배열을 성장 시키거나 축소 해야하는 경우 새 수의 항목으로 새 배열을 만들고 원하는 항목을 이전 배열에서 새 배열로 복사해야합니다.
예를 들어, 배열을 가져 와서 짝수 요소 만 복사하려고한다고 가정하십시오.
int[] a = new int[] {0,1,2,3,4,5,6,7,8,9};
int[] a2 = new int[a.Length / 2];
int counter = 0;
for (int i = 0; i < a.Length; i = i + 2)
{
a2[counter++] = a[i];
}
그런 다음 항상 A2를 다시 할당 할 수 있습니다.
a = a2;
당신이 사용할 수있는 System.Collections.Generic.List<T>
또한 RESIZABLE 컬렉션을 제공합니다 .ToArray()
필요한 경우 일반 배열을 반환하는 방법.
목록을 사용한 다음 배열로 변환하십시오.
실제로이 예에서는 StockInfo {StockInfo, 가격, 항목 이름}에 대한 클래스 또는 struct가 있어야합니다. 그러면 데이터를 목록에 입력해야합니다. 마지막으로 목록의 ToArray 메소드를 사용하여 StockInfo []로 변환 할 수 있습니다.
당신은 사용할 수 있습니까? 배열 목록 대신에? 필요에 따라 크기를 조정합니다.
나는 같은 문제를 겪었지만 유형을 변경할 수 없었고 존재하는 API 클래스를 확장 한 후 배열에 붙어 있어야했습니다. 다음은 존재하는 배열을 확장하는 간단한 템플릿 방법입니다.
public static T[] ExtendArray<T> ( T[] array , uint index) where T:new()
{
List<T> list = new List<T>();
list.AddRange(array);
while (list.Count < index) {
list.Add(new T());
}
return list.ToArray();
}
위의 것도 참조하십시오 초기화 기본 생성자가있는 요소.
당신은 당신이 기대할 수있는 가장 큰 배열만큼 큰 배열을 사용하여 배열을 크기를 조정할 수없는 '문제'를 해결할 수 있습니다. 이것은 구조화 된 프로그래밍이 아닌 해킹으로 간주됩니다!
System.linq에 액세스 할 수있는 경우 Handy Extension 방법을 사용할 수 있습니다. 동의 배열과 같은 ienumerable 객체의 경우. 배열을 확장 할 수 있습니다.
int[] result = new int[] { 1, 2 };
int[] extend = new int[] { 3, 4 };
result = result.Concat(extend).ToArray();
foreach (int i in result)
{
Console.WriteLine(i.ToString());
}
결과:
1
2
3
4