行和列多维数组的java [英] Rows and columns with multidimensional array java

查看:147
本文介绍了行和列多维数组的java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提出/创建我正在高中班一个基于Java的游戏,因为它是逃避我的逻辑。

的什么,我试图做的目的是做一个游戏,在上一个JPanel一个24x24的网格随机生成一个地形广场(因为我发现,是最常见的对象画上)都在它自己的不受外界(用户)的帮助。

我通过尝试此for循环,将采取COORDS [] [],并标记一个值防爆一定的虚的位置:地板

但是当我运行它,它是所有在0,0漆的第一方20×20

现在我听说/读,有爪哇内没有多维数组喜欢为例的Small Basic。但我不明白的阵列里的数组是专门做。在这方面的一些解释是大大AP preciated。

还有任何替代建议,要么使其更易于/我的程序更顺畅将AP最多preciated因为我此刻的新手程序员。

我已经看过了解决我的问题在这些职位,但都无济于事。

<一个href=\"http://stackoverflow.com/questions/2707357/how-to-create-dynamic-two-dimensional-array-in-java\">how在Java中创建动态二维数组?

<一个href=\"http://stackoverflow.com/questions/10751603/how-to-insert-values-in-two-dimensional-array-programmaticaly\">How在二维数组programmaticaly插入值?

<一个href=\"http://stackoverflow.com/questions/11243774/how-to-automatically-populate-a-2d-array-with-numbers\">how自动填充数字的二维数组

<一个href=\"http://stackoverflow.com/questions/5022824/how-to-fill-a-two-dimensional-arraylist-in-java-with-integers\">How为整数,以填补一个二维的ArrayList在Java?

<一个href=\"http://stackoverflow.com/questions/9874121/arraylist-toarray-method-in-java\">ArrayList.toArray()方法的Java

<一个href=\"http://stackoverflow.com/questions/5061721/how-can-i-dynamically-add-items-to-a-java-array\">How我可以动态地将项目添加到Java数组?

<一个href=\"http://stackoverflow.com/questions/10052917/automatic-adding-of-elements-to-an-array\">Automatic添加元素的一个数组

下面是code应该做这个动作对我来说,但目前未能块:

 类的GamePanel继承JPanel
{公众的GamePanel()
{
    的setBounds(115,93,480,480);
    的setBackground(Color.white);
}私人随机发生器=新的随机();INT楼= 0; //初始化变量地板以备以后使用零
INT污垢= 1;
INT石= 2;
INT水= 3;
INT熔岩= 4;
INT铁= 5;
INT金= 6;
INT翡翠= 7;
INT金刚石= 8;
INT基岩= 9;INT宽度= 24;
INT高度= 24;
INT X,Y; //我的X&安培;为坐标Y变量INT [] [] = COORDS新INT [宽度] [高]; //我的数组,我想存储在绘画以后使用的坐标
INT [] =地形地板{,泥土,石头,水,熔岩,铁,
                            黄金,翡翠,钻石,基岩}; //我的地形,将决定涂料的颜色公共无效mapGen()//应该怎样纪念/生成的JPanel
{
    为(X = 0; X&下; =宽; X ++)
    {        对于(Y = 0; Y&LT; =身高; Y ++)
        {            INT Z = generator.nextInt(20);所述随机化//部分            如果(z,其中,11例)
            {
                COORDS [X] [Y] =地形[0]; //标志着坐标地板            }            其他{};        }
    }        COORDS [0] [0] =地形[0]; //套坐标0,0地板//需要有这些始终是地板
        COORDS [24] [24] =地形[0]; //组协调24,24地板// ^^^^^^^^^^
}
@覆盖
公共无效的paintComponent(图形G)//什么都会画上它被赋予了每个网格正方形20×20
{
    super.paintComponent方法(G);    如果(COORDS [X] [Y] ==地形[楼])
    {
    g.setColor(新颜色(46,46,46));
    g.fillRect((X * 20),(Y * 20),20,20);
    }    其他{};}
} //结束的GamePanel

这不是在Java编程认为是基本的任何及所有条款/ code,将极大如果他们的响应,其中解释AP preciated。

请尽可能详细和具体在尽可能的响应,我仍然在学习Java和它的运作。


修改的结果
所以这code有些作品,但它没有完成它应该的。

该程序的方式(部分至少)应该工作是循环的推移每个20×20平方被标记为这些特定坐标的具体地形再由psented $ P $COORDS [X] [Y]

然后,它标志着坐标后,它应该在的paintComponent

之内回去漆分别为每它分配的地形

在做这个程序应该已经创建了一个地图玩家通过工作他们的方式。

相反,它的作用是覆盖整个的JPanel只用别人的地形[污垢]和无

下面是该方案的工作模型,它的问题:

 进口java.awt中的*。
进口的javax.swing *。
进口的java.util。*;公共类的GamePanel继承JPanel
{    公众的GamePanel()
    {
        的setBounds(115,93,480,480);
        的setBackground(Color.white);
    }    私人随机发生器=新的随机();    INT楼= 0; //初始化变量地板以备以后使用零
    INT污垢= 1;
    INT石= 2;
    INT水= 3;    INT宽度= 24;
    INT高度= 24;
    INT X,Y; //我的X&安培;为坐标Y变量    INT [] [] = COORDS新INT [宽度] [高]; //我的数组,我想存储在绘画以后使用的坐标
    INT [] =地形地板{,泥土,石头,水}; //我的地形,将决定涂料的颜色    公共无效mapGen()//应该怎样纪念/生成的JPanel
    {
        为(X = 0; X&下; =宽; X ++)
        {            对于(Y = 0; Y&LT; =身高; Y ++)
            {                INT Z = generator.nextInt(20);所述随机化//部分                如果(z,其中,11例)
                {
                    COORDS [X] [Y] =地形[0]; //应该标记坐标地板                }                如果(Z == 12)
                {
                    COORDS [X] [Y] =地形[3]; //应该标记的坐标作为水
                }                如果(Z&GT; = 13安培;&安培; z,其中,17例)
                {
                    COORDS [X] [Y] =地形[2]; //应当标注坐标如石
                }                如果(Z&GT; = 18安培;&安培; z,其中,= 20)
                {
                    COORDS [X] [Y] =地形[1]; //应当标注坐标如粪​​土
                }                    COORDS [0] [0] =地形[0]; //套坐标0,0地板//需要有这些始终是地板
                    COORDS [24] [24] =地形[0]; //组协调24,24地板// ^^^^^^^^^^
            }
        }
    }
    @覆盖
    公共无效的paintComponent(图形G)//什么都会画上它被赋予了每个网格正方形20×20
    {
        super.paintComponent方法(G);        对于(INT X = 0; X&LT;宽度; X ++)
        {
            对于(INT Y = 0; Y&LT;高度; Y ++)
            {
                如果(COORDS [X] [Y] ==地形[楼])//应该绘制明码坐标地板颜色
                {
                    g.setColor(新颜色(46,46,46));
                    g.fillRect((X * 20),(γ* 20),20,20);                }                如果(COORDS [X] [Y] ==地形[污垢]); //应该绘制明码坐标的污垢颜色
                {
                    g.setColor(新颜色(135,102,31));
                    g.fillRect((X * 20),(γ* 20),20,20);
                }                如果(COORDS [X] [Y] ==地形[石])//应该绘制石材颜色明码坐标
                {
                    g.setColor(新颜色(196196196));
                    g.fillRect((X * 20),(Y * 20),20,20);
                }                如果(COORDS [X] [Y] ==地形[水])//应该绘制明码坐标水色
                {
                    g.setColor(新颜色(85199237));
                    g.fillRect((X * 20),(Y * 20),20,20);
                }
            }
        }    } //结束的paintComponent公共静态无效的主要(字串[] args)
{
    的GamePanel面板=新的GamePanel();
    JFrame的帧=新的JFrame();
    frame.setSize(480,480);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    。frame.getContentPane()加(面板);
    frame.setVisible(真);} //主到底} //结束的GamePanel


解决方案

两个要点:


  • 绘画是破坏性的,每次的paintComponent 被调用,您预计将重绘整个组件的状态

  • X 不要在你的的paintComponent ,他们是他们经过相同的值 mapGen 被称为

相反,你的绘制方法可以看起来更像...

  @覆盖
保护无效paintComponent(图形G)//什么都会画上它被赋予了每个网格正方形20×20
{
    super.paintComponent方法(G);    为(中间体X = 0; X&下;宽度; X ++){
        对于(INT Y = 0; Y&LT;高度; Y ++){
            如果(COORDS [X] [Y] ==地形[楼]){
                g.setColor(新彩(46,46,46));
                g.fillRect((X * 20),(γ* 20),20,20);
            }其他... {
                // ...
            }
        }
    }}

请参阅AWT 绘画和Swing 和的表演风俗画了解更多详情

就个人而言,在 mapGen ,我想创建一个的BufferedImage 这是 24 * 20 24 * 20 高,油漆全部瓷砖它和在的paintComponent 方法,绘制图片

基于可运行的例子...


  • mapGen 永远不会被调用,所以在坐标总是 0 或`地板

  • 为(X = 0; X&LT; =宽度; X ++){为(Y = 0; Y&LT; =高度; Ÿ++){将导致 IndexOutOfBoundsException异常作为数组是基于零( 0-23

  • COORDS [24] [24] =地形[0]; 将导致 IndexOutOfBoundsException异常出于同样的原因以上。

一旦纠正,code可生成类似...

地球的随机补丁

I am making/creating a Java based game for a High School class I am taking and the logic for it is escaping me.

The object of what I am trying to do is make a game that randomly generates a "terrain" square in a 24x24 grid on a JPanel (as I have found that is the most common Object to paint on) all on it's own without outside (user) help.

I am attempting this through a "for" loop that will take "coords[][]" and mark a certain "imaginary" position with a value Ex: floor.

But when I run it all it does is paint the very first 20x20 square at 0,0.

Now I have heard/read that there is no "multi-dimensional" array inside of Java like in for example Small Basic. But I do not understand what an array inside of an array does specifically. Some explanation on this front would be greatly appreciated.

Also any alternative suggestions that would either make it easier/smoother for my program would be most appreciated as I am a novice programmer at the moment.

I have looked for the solution to my problem in these posts but to no avail.

how to create dynamic two dimensional array in java?

How to insert values in two dimensional array programmaticaly?

how to automatically populate a 2d array with numbers

How to fill a two Dimensional ArrayList in java with Integers?

ArrayList.toArray() method in Java

How can I dynamically add items to a Java array?

Automatic adding of elements to an array

Here is the block of code that should be doing this action for me but is currently failing:

class gamePanel extends JPanel
{   

public gamePanel()
{
    setBounds(115,93,480,480);
    setBackground(Color.white);
}

private Random generator = new Random();    

int floor = 0; //initializes the variable floor to zero for later use
int dirt = 1;
int stone = 2;
int water = 3;
int lava = 4;
int iron = 5;
int gold = 6;
int emerald = 7;
int diamond = 8;
int bedrock = 9;

int width = 24;
int height = 24;    
int x, y; // my x & y variables for coordinates

int[][] coords = new int[width][height]; //my array that I want to store the coordinates for later use in painting


int[] terrain = {floor, dirt, stone, water, lava, iron,       
                            gold, emerald, diamond, bedrock}; //my terrain that will determine the color of the paint

public void mapGen() //what should mark/generate the JPanel
{
    for(x = 0; x <= width; x++)
    {

        for(y = 0; y <= height; y++)
        {

            int z = generator.nextInt(20);// part of the randomization

            if(z <= 11)
            {
                coords[x][y] = terrain[0]; //marks the coordinates as floor

            }

            else{};

        }
    }

        coords[0][0] = terrain[0]; // sets coordinate 0,0 to floor //need to have these always be floor
        coords[24][24] = terrain[0]; // sets coordinate 24,24 to floor //^^^^^^^^^^
}   


@Override
public void paintComponent(Graphics g)//what will paint each 20x20 square on the grid what it is assigned
{
    super.paintComponent(g);

    if(coords[x][y] == terrain[floor])
    {
    g.setColor(new Color(46,46,46));
    g.fillRect((x*20),(y*20),20,20);    
    }

    else{};

}
}//end gamePanel

Any and all terms/code that are not considered "basic" in Java programming, would be greatly appreciated if they where explained in the response.

Please be as detailed and specific in your response as possible as I am still learning Java and it's workings.


EDIT
So this code somewhat works but it is not accomplishing what it should.

The way this program (portion at least) should work is as the loop goes each individual 20x20 square is marked as a specific terrain for those specific coordinates represented by "coords[x][y]"

Then after it has marked the coordinates it should go back and paint each respectively for it's assigned "terrain" within the "paintComponent"

In doing this the program should have created a map for the player to work their way through.

Instead what it does is cover the whole JPanel with only "terrain[dirt]" and none of the others

Here is a working model of the program and it's problem:

import java.awt.*;
import javax.swing.*;
import java.util.*;

public class gamePanel extends JPanel
{   

    public gamePanel()
    {
        setBounds(115,93,480,480);
        setBackground(Color.white);
    }

    private Random generator = new Random();    

    int floor = 0; //initializes the variable floor to zero for later use
    int dirt = 1;
    int stone = 2;
    int water = 3;

    int width = 24;
    int height = 24;    
    int x, y; // my x & y variables for coordinates

    int[][] coords = new int[width][height]; //my array that I want to store the coordinates for later use in painting


    int[] terrain = {floor, dirt, stone, water}; //my terrain that will determine the color of the paint

    public void mapGen() //what should mark/generate the JPanel
    {
        for(x = 0; x <= width; x++)
        {

            for(y = 0; y <= height; y++)
            {

                int z = generator.nextInt(20);// part of the randomization

                if(z <= 11)
                {
                    coords[x][y] = terrain[0]; //should mark the coordinates as floor

                }

                if(z == 12)
                {
                    coords[x][y] = terrain[3];//should mark the coordinates as water
                }

                if(z >= 13 && z <= 17)
                {
                    coords[x][y] = terrain[2];//should mark the coordinates as stone
                }

                if(z >= 18 && z <= 20)
                {
                    coords[x][y] = terrain[1];//should mark the coordinates as dirt
                }

                    coords[0][0] = terrain[0]; // sets coordinate 0,0 to floor //need to have these always be floor
                    coords[24][24] = terrain[0]; // sets coordinate 24,24 to floor //^^^^^^^^^^
            }
        }


    }   


    @Override
    public void paintComponent(Graphics g)//what will paint each 20x20 square on the grid what it is assigned
    {
        super.paintComponent(g);

        for(int x = 0; x < width; x++)
        {
            for(int y = 0; y < height; y++)
            {
                if(coords[x][y] == terrain[floor])//should paint the floor color at marked coordinates
                {
                    g.setColor(new Color(46,46,46));
                    g.fillRect((x*20), (y*20), 20, 20); 

                }

                if(coords[x][y] == terrain[dirt]);//should paint the dirt color at marked coordinates
                {
                    g.setColor(new Color(135,102,31));
                    g.fillRect((x*20), (y*20), 20, 20);
                }

                if(coords[x][y] == terrain[stone])//should paint the stone color at marked coordinates
                {
                    g.setColor(new Color(196,196,196));
                    g.fillRect((x*20),(y*20),20,20);
                }

                if(coords[x][y] == terrain[water])//should paint the water color at marked coordinates
                {
                    g.setColor(new Color(85,199,237));
                    g.fillRect((x*20),(y*20),20,20);
                }
            }
        }

    }//end paintComponent

public static void main(String[] args)
{
    gamePanel panel = new gamePanel();
    JFrame frame = new JFrame();
    frame.setSize(480,480);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(panel);
    frame.setVisible(true);

}//end main

}// end gamePanel

解决方案

Two main points:

  • Painting is destructive, each time paintComponent is called, you are expected to repaint the entire component state
  • x and y don't change in your paintComponent, they are the same value they were after mapGen is called

Instead, your paint method could look more like...

@Override
protected void paintComponent(Graphics g)//what will paint each 20x20 square on the grid what it is assigned
{
    super.paintComponent(g);

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            if (coords[x][y] == terrain[floor]) {
                g.setColor(new Color(46, 46, 46));
                g.fillRect((x * 20), (y * 20), 20, 20);
            } else ... {
                //...
            }
        }
    }

}

See Painting in AWT and Swing and Performing Custom Painting for more details

Personally, in mapGen, I would create a BufferedImage which was 24*20 wide and 24*20 high, paint all the tiles to it and the in the paintComponent method, paint the image

Based on runnable example...

  • mapGen is never called, so the values in coord are always 0 or `floor
  • for (x = 0; x <= width; x++) { and for (y = 0; y <= height; y++) { will cause an IndexOutOfBoundsException as arrays are zero based (0-23)
  • coords[24][24] = terrain[0]; will cause an IndexOutOfBoundsException for the same reason above.

Once corrected, the code can generate something like...

这篇关于行和列多维数组的java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆