当我尝试在程序中拍摄彩弹时,出现上述问题。类(Paintballs)代码如下。未处理的异常。指数超出范围。必须是非负数且小于集合的大小。参数名称:索引
class Paintballs
{
public List<Point> myClick;
public Paintballs()
{
myClick = new List<Point>();
}
public void add(Point location)
{
myClick.Add(location);
}
public void paint(Graphics g)
{
foreach (Point p in myClick)
{
g.FillEllipse(Brushes.Blue, p.X, p.Y, 20, 20);
}
}
public Point getPoints(int hit)
{
return myClick[hit];
}
}
当我调试程序,错误是在getPoints方法“返回了MyClick哈工大]就行了。下面是我的Form1上。
namespace AmazingPaintball
{
public partial class Form1 : Form
{
Random positionX = new Random();
Random positionY = new Random();
Target einstein;
int count = 0;
Paintballs pBalls = new Paintballs();
Stopwatch stopwatch = new Stopwatch();
//Foreach loop
//Draw paintballs first
//then target
SoundPlayer wavPlayer = new SoundPlayer();
public Form1()
{
InitializeComponent();
Point point = new Point(positionX.Next(0, 638), positionY.Next(0, 404));
einstein = new Target(point);
ptrEinstein.Location = point;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
pBalls.paint(e.Graphics);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
ptrEinstein.Location = einstein.Move(e.KeyData);
pictureBox1.Update();
pictureBox1.Refresh();
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
pBalls.add(e.Location);
pictureBox1.Refresh();
count++;
Point shotHit = pBalls.getPoints(count);
if (ptrEinstein.Location == shotHit)
{
stopwatch.Stop();
MessageBox.Show("It took " + count + " shots and " + stopwatch.Elapsed + " seconds to hit the target");
}
}
private void Form1_Load(object sender, EventArgs e)
{
stopwatch.Start();
}
}
}
在Form1,这个问题似乎是。在picturebox1_MouseClick
事件的count
可变我不知道我是否应该保持在0或1,请让我知道,谢谢
尝试增量次数。看起来你试图让总索引大于数组大小。由于这个特殊的例子,你可以在List中使用Last()方法。 – 2014-08-30 15:03:08