【发布时间】:2018-01-19 02:09:11
【问题描述】:
我正在尝试使用名为“insert”的预先编写的方法填充一个名为“items”的字符串数组。
该项目已预先编写代码“b.insert("apple");”等等等等,给出的方法是“public void insert(T item)”。我必须在这种方法中编写代码才能使“插入”功能起作用。我必须将“item”传递给“items”数组,但我的 for 循环只是给了我 10 次输出“milk”。因此,我知道“item”值只是更改为插入方法中传递的最后一个字符串。我是否必须编写一个嵌套的 for 循环,其中“item”是一个计数器?在这种情况下,“item”不能是计数器,因为它是字符串类型。我应该将“项目”转换为数组吗?
我不知道为什么这么一个看似简单的任务让我难倒了我已经做了好几个小时了,此时我只想为了理智起见把它整理出来。
提前致谢
class Program
{
static void Main(string[] args)
{
BoundedBag<string> b = new BoundedBag<string>("ShoppingList", 10);
b.insert("apple");
b.insert("eggs");
b.insert("milk");
Console.WriteLine(b);
Console.ReadKey();
}
}
public interface Bag<T> where T : class
{
void insert(T item);
string getName();
bool isEmpty();
}
public class BoundedBag<T> : Bag<T> where T : class
{
private string bagName; // the name of the bag
protected int size; // max size of the bag
private int lastIndex;
protected T[] items;
public BoundedBag(string name, int size)
{
bagName = name;
this.size = size;
rnd = new Random();
items = new T[size];
}
public string getName()
{
return bagName;
}
public bool isEmpty()
{
return lastIndex == -1;
}
public bool isFull()
{
if(items.Length >= size)
{
return true;
}
else { return false;}
}
public void insert(T item)
{
// fill in the code as directed below:
// insert item into items container
// throws FullBagException if necessary
for (int i = 0; i < size; i++)
{
items[i] = item;
}
}
}
【问题讨论】:
-
在阅读How to Ask 并接受tour 后,尝试将冗长的漫谈提炼成一个简洁的问题陈述并提出一个简洁的问题
-
非常感谢您的帮助..
标签: c# arrays loops for-loop parameters