我试图仅为通过开关的 for 循环的第一次迭代设置特定图像。对于 case 'f'
我想在第一次迭代时添加不同的图像。
我该怎么做?是否有可能在开关内进行跟踪?
for (char c : symbols) {
switch (c) {
case 'X':
g2.setColor(Color.BLACK);
g2.drawImage(wallImg, x, y, width, height, null);
break;
case 's':
g2.setColor(Color.GREEN);
g2.drawImage(snakeImg, x, y, width, height, null);
break;
case 'f':
g2.setColor(Color.ORANGE);
g2.drawImage(burgerImg, x, y, width, height, null);
break;
case '.':
g2.setColor(Color.WHITE);
g2.fillRect(x, y, width, height);
break;
case '\n':
y += height;
}
最佳答案
添加一个标志来查看是否已迭代,然后在 switch-case 中采用 if 语句来解释它,如下所示:
boolean flag = false;
for (char c : symbols) {
switch (c) {
case 'X':
g2.setColor(Color.BLACK);
g2.drawImage(wallImg, x, y, width, height, null);
break;
case 's':
g2.setColor(Color.GREEN);
g2.drawImage(snakeImg, x, y, width, height, null);
break;
case 'f':
//check to see if your flag is true/false
if(flag){
g2.setColor(Color.ORANGE);
g2.drawImage(burgerImg, x, y, width, height, null);
}else{
//set first image
flag = true;
}
break;
case '.':
g2.setColor(Color.WHITE);
g2.fillRect(x, y, width, height);
break;
case '\n':
y += height;
break;
}
关于java - 为第一轮 Switch Java 制作 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47706293/