Is there anyway to shorten if else statements inst

2019-08-09 01:21发布

问题:

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]

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

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)

回答1:

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

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

or

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

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



回答2:

In addition to a Map suggested elsewhere, you could just use an array; you'll need to keep track of the index of the current image:

int[5] nextImageList
  = { 2, ?, 4, 5, 4 }

next = nextImageList[currentImageIndex];
currentImage = nekoPics[next];
currentImageIndex = next;

No 'if' needed after you initialize currentImage and currentImageIndex. I wasn't sure if 1 was a valid index anywhere, if not, anything can go in the 1 slot in the array.



回答3:

It would probably be easier to code if you stop that cat from getting in front of your screen...

Seriously, though, you could solve this by making an object that defines your sequence of pictures.



回答4:

I was going to post an answer similar to rcook, using an array. I see it as the simplest solution to understand.

His answer, however, has a slight mistake concerning the array dimensions. I'm posting this for completeness, but credit should be directed to him.

// Elsewhere, in your initialization:
int currentImageIndex = 0; // Assuming [0] is your first image.
int[] nextImageList = { 2, -1, 4, -1, 5, 4 };
// Given the current index, this array will direct you
// to the next image index. Those -1 are unknown (to us).
// Set them to the values you need.

private void scratch() {
    for (int i = xPos; i < getWidth(); ) {
        xPos = i;

        // Swap images.
        currentImageIndex = nextImageList[currentImageIndex];
        currentImage = nekoPics[currentImageIndex];

        // What else you were doing here.
    }
}