无论如何要缩短if else语句而不是圈内 [英] Is there anyway to shorten if else statements instead of going in circles

查看:115
本文介绍了无论如何要缩短if else语句而不是圈内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一只猫穿过屏幕,并在屏幕中间停留两次。我当前的代码看起来像

I have a cat that runs across the screen and stops to scratch in the middle of the screen twice. My current code looks like

private void scratch(){
for (int i = xPos; i < getWidth(); i+=0) {
    xPos = i;
    // swap images
    if (currentImage == nekoPics[0]) 
        currentImage = nekoPics[2];
    else if (currentImage == nekoPics[2])
        currentImage = nekoPics[4];
    else if (currentImage == nekoPics[4])
        currentImage = nekoPics[5];
    else if (currentImage == nekoPics[5])
        currentImage = nekoPics[4];
    else if (currentImage == nekoPics[4]) 
        currentImage = nekoPics[5];
    else 
        currentImage = nekoPics[0]

有没有更简单的方法制作if else语句,而不是让他们进入这样一个巨大的圈子?

Is there an easier way to make the if else statements than have them going in a huge circle like this?

提前谢谢
(PS:我假设你可以用一个计数器做这个某种,但我不太确定如何去做,任何帮助都表示赞赏)

Thanks in advance (PS : I assume you could do this with a counter of some sort, but I wasn't so sure on how to go about this, any help is appreciated)

推荐答案

你可以保留当前图像的索引,并在每次迭代时增加它,例如:

You may keep the index of the current image, and increment it on each iteration, for instance:

currentImage = nekoPics[currentIndex%6];
currentIndex++;

currentImage = nekoPics[currentIndex];
if (++currentIndex==6) currentIndex=0;

这要求nekoPics中的图像按照动画的顺序排序。

This requires that images in nekoPics be sorted according to the order of the animation.

这篇关于无论如何要缩短if else语句而不是圈内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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