【问题标题】:How can I populate a string array with a parameter method C#如何使用参数方法 C# 填充字符串数组
【发布时间】: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


【解决方案1】:

您只想在插入时将一项插入数组,因此根本不应该有循环。使用 lastIndex 字段将一项插入到数组中的适当位置:

public void insert(T item)
{
    // fill in the code as directed below:
    // insert item into items container
    // throws FullBagException if necessary

    if(isFull())
    {
       throw new FullBagException();
    }

    items[++lastIndex] = item;
}

不幸的是,您的 isFull 方法也损坏了,除非您更改构造函数,否则您的 isEmpty 方法将无法正常工作。

public BoundedBag(string name, int size)
{
     bagName = name;
     this.size = size;
     items = new T[size];
     lastIndex = -1;
}

public bool isFull()
{
    return lastIndex == size - 1;
}

【讨论】:

  • 感谢您的回复,希望我能支持您。项目[++lastIndex] = 项目;是我完成这项工作所需要的。在使用循环之前,我尝试过类似的事情,但你使用了我完全忽略的 lastIndex。再次感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
  • 2021-01-23
  • 1970-01-01
相关资源
最近更新 更多