我制作了一个二维数组,需要将元素[i][j] = 0,1,2,3,4,
或5
映射到要打印的彩色像素。这就是我所拥有的。
像素数组,表示不同颜色的整数值
static int [][] marioArray = new int [][]{
{0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0},
{0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0},
{0,0,0,0,2,2,2,3,3,4,3,0,0,0,0,0},
{0,0,0,2,3,2,3,3,3,4,3,3,3,0,0,0},
{0,0,0,2,3,2,2,3,3,3,4,3,3,3,0,0},
{0,0,0,0,2,3,3,3,3,4,4,4,4,0,0,0},
{0,0,0,0,0,3,3,3,3,3,3,0,0,0,0,0},
{0,0,0,0,1,1,5,1,1,5,1,1,0,0,0,0},
{0,0,0,1,1,1,5,1,1,5,1,1,1,0,0,0},
{0,0,1,1,1,1,5,5,5,5,1,1,1,1,0,0},
{0,0,3,3,1,5,3,5,5,3,5,1,3,3,0,0},
{0,0,3,3,3,5,5,5,5,5,5,3,3,3,0,0},
{0,0,3,3,5,5,5,5,5,5,5,5,3,3,0,0},
{0,0,0,0,5,5,5,0,0,5,5,5,0,0,0,0},
{0,0,0,2,2,2,0,0,0,0,2,2,2,0,0,0},
{0,0,2,2,2,2,0,0,0,0,2,2,2,2,0,0}};
打印像素的方法
public static void drawPixl (Graphics g, int x, int y, int scale, Color color)
{
g.setColor(color);
g.fillRect(x,y,scale,scale);
}
我尝试使用我的数组进行for循环
public static void drawMario (Graphics g, int x, int y, int scale)
{
int i;
for(i = 0, i < 16, i++){
int j;
for(j = 0, j <16, j++){
if (marioArray[i][j] == 1){
drawPixl(g,scale*i,scale*j,scale,Color.red);}
if (marioArray[i][j] == 2){
drawPixl(g,scale*i,scale*j,scale,new Color(94, 38, 18));}
if (marioArray[i][j] == 3){
drawPixl(g,scale*i,scale*j,scale,new Color(255, 193, 37));}
if (marioArray[i][j] == 4){
drawPixl(g,scale*i,scale*j,scale,Color.black);}
if (marioArray[i][j] == 5){
drawPixl(g,scale*i,scale*j,scale,Color.blue);}
else;
}
}
}
我尝试了一个嵌套的for循环,一个增强的for循环和一个while循环,但我没有运气,我猜
修改
我测试了drawPixl()
,它运行正常。 drawMario
中每个for循环旁边都会弹出唯一的错误,其中包含:
1. Syntax error on token '<', ( expected
2. Syntax error, insert ';;) Statement' to complete ForStatement
3. the method i(int, int) is undefined for the type Animation
此外,int scale用于定位像素的位置并为其提供正确的大小
答案 0 :(得分:2)
在for
循环中使用分号:
int i;
for(i = 0; i < 16; i++){
int j;
for(j = 0; j <16; j++){
答案 1 :(得分:2)
public static void drawMario (Graphics g, int x, int y, int scale)
{
int i;
//for(i = 0, i < 16, i++){ --> HERE IS THE ERROR, YOU NEED TO ADD ; AFTER 0 AND 16
for(i = 0; i < 16; i++){ // --> AFTER ADDING ;
int j;
//for(j = 0, j <16, j++){ --> HERE IS THE ERROR, YOU NEED TO ADD ; AFTER 0 AND 16
for(j = 0; j <16; j++){ // --> AFTER ADDING ;
if (marioArray[i][j] == 1){
drawPixl(g,scale*i,scale*j,scale,Color.red);}
if (marioArray[i][j] == 2){
答案 2 :(得分:2)
我会采用更有活力的方法。在这里,您将永远不会获得AOB异常,并且您不必在输入数组大小更改时更改循环参数。
for(int i = 0; i < marioArray.length; i++){
int [] row = marioArray[i];
for(int j = 0; j <row.length; j++){
Color color = null;
switch(row[j]){
case 1:
color = Color.red; break;
case 2:
color = Color(94, 38, 18); break;
...
}
if(color!=null){
drawPixl(g,scale*i,scale*j,scale,color);
}
}
}
您的代码更干净,在switch语句中您只能选择Color
,因此您不必将整个drawPixl
方法复制到每一行。
在Java中,您不必在循环之外声明循环索引,除非您在循环之外以某种方式需要它。