【问题标题】:How to add integer to integers in array如何将整数添加到数组中的整数
【发布时间】:2014-04-07 21:40:23
【问题描述】:

我想要完成的是将1 添加到shipX 数组列表中的所有数字中,问题是,如何?我想在调用 move() 方法时执行此操作,但我将如何实现这一点,因为我是数组的新手

class Ship
{
    public void paint(Graphics g)
    {
        int shipX[] = {500,485,500,515,500};
        int shipY[] = {500,485,455,485,500};
        g.setColor(Color.cyan);
        g.fillPolygon(shipX, shipY, 5);
    }
    public void move()
    {
    }
}

【问题讨论】:

  • 你应该使用 ArrayList 而不是 int array

标签: java arrays list addition


【解决方案1】:

首先,您必须将数组移动到paint() 的本地范围之外的点并移到类中,以便move() 可以访问当前值。您将增加 move() 方法并调用您用来重绘组件的任何例程。

class Ship
{
    //make your polygon points members of the class
    //so that you can have state that changes
    //instead of declaring them in the paint method
    int shipX[] = {500,485,500,515,500};
    int shipY[] = {500,485,455,485,500};
    //set these to the amount you want per update. They can even be negative 
    int velocityX = 1;
    int velocityY = 1;

    public void paint(Graphics g)
    {
        g.setColor(Color.cyan);
        g.fillPolygon(shipX, shipY, 5);
    }

    public void move()
    {
        //add 1 to each value in shipX
        for (int i=0; i<shipX.length; i++)
        {
            shipX[i] += velocityX;
        }
        //add 1 to each value in shipY
        for (int i=0; i<shipY.length;i++)
        {
            shipY[i] += velocityY;
        }
        //call whatever you use to force a repaint
        //normally I would assume your class extended
        //javax.swing.JComponent, but you don't show it in your code
        //if so, just uncomment:
        //this.repaint();
    }
}

虽然我应该指出JComponent 上的repaint() 方法确实需要从正确的Swing 线程中调用,正如this 答案中所指出的那样。

如果您还尝试为运动设置动画,您可以查看 Swing 计时器上的 Java Tutorial 以按计划调用您的 move() 方法。您还可以在按钮上使用ActionListener 来控制Timer,或者在按钮上使用每次点击手动移动对象一次。

【讨论】:

  • @BrandonG 我进行了更改,为您提供 X 和 Y 方向的速度。您可以手动设置它们或在代码的其他地方动态调整它们
  • 正是我在寻找什么,我根本没有使用数组的经验,所以这对我未来的项目和这个项目有很大帮助。很难从矩形过渡到多边形!但是最后一件事,如果我想放慢速度,我可以将 I++ 更改为 I--
  • @BrandonG 将代码更改为shipX[i]-- 不会减慢您的移动速度,它实际上会反转它的方向!要减慢它的速度,您应该修改 velocityXvelocityY 值(但负值将反转方向,而不是减少)。如果1 仍然过快,我建议放慢您用于计时器的任何内容,或者您​​可以切换到使用floats,但是我们要么必须在move() 方法中重新计算数学,要么我们必须切换到使用java.awt.Path2D 的实现(不是一个坏主意)
【解决方案2】:

你所要做的就是遍历数组并修改每个索引的值:

for (int i = 0; i < shipX.length; i++)
{
    shipX[i]++;
}

【讨论】:

    【解决方案3】:

    一个一个地增加数字...

    for (i=0; i<shipX.length; i++)
    {
       shipX[i]++; // same as shipX[i] = shipX[i] +1
    }
    
    for (i=0; i<shipY.length;i++)
    {
       shipY[i]++;
    }
    

    【讨论】:

    • shipY.length()?您是否测试过该代码。它是一个属性,而不是一个方法。
    • 你说得对,我应该是 (i=0; i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多