简体   繁体   中英

Why my switch don't work?

I'm making a chronometer(10 seconds) using System.currentTimemillis . And I have in a method that is refreshed 10 times per second the following code:

Start is the starting time of the activity, that it's "asked" in the onCreate method. I know that Integer.parseInt(Long.toString(y)) works because when I do System.out.println(Integer.parseInt(Long.toString(y))); it returns me the time correctly.

So, my problem is that i don't know why the swich don't work properly.

long y=System.currentTimeMillis()-start;

switch (Integer.parseInt(Long.toString(y))) {           
    case 1000:
        time.setText("3");
        time.setAnimation(anim);
        break;

    case 2000:
        time.setText("2");
        time.setAnimation(anim);
        break;

    case 3000:
        time.setText("1");
        time.setAnimation(anim);
        break;

    case 4000:
        time.setText("GOOO!");
        time.setAnimation(anim);
        count.setVisibility(View.VISIBLE);
        cuenta = 0;
        count.setText("0");
        break;

    case 5000:
        time.setText("1");
        time.setAnimation(anim);
        break;

    case 6000:
        time.setText("2");
        time.setAnimation(anim);
        break;

    case 7000:
        time.setText("3");
        time.setAnimation(anim);
        break;

    case 8000:
        time.setText("4");
        time.setAnimation(anim);
        break;

    case 9000:
        time.setText("5");
        time.setAnimation(anim);
        break;

    case 10000:
        time.setText("Time!");
        time.setAnimation(anim);
        count.setVisibility(View.INVISIBLE);
        break;
}

Because it won't exactly give these numbers 1000,2000,3000...

If the number give more or less then case will fail

Edit:

Try this

public static boolean isBetween(int x, int lower, int upper) {
  return lower <= x && x <= upper;
}

if (isBetween(num, 0, 1000)) {

  // do something

} else if (isBetween(num, 1001, 2000)) {

// do domething

}
...

...

The problem with your code is that you check for a special time. I think you may want to use a code like this:

Integer val = Integer.parseInt(Long.toString(y));
if(val<1000) {
    time.setText("3");
    time.setAnimation(anim);
} else if(val<2000) {
    time.setText("2");
    time.setAnimation(anim);
} else if(val<3000) {
    time.setText("1");
    time.setAnimation(anim);
} else if(val<4000) {
    time.setText("GOOO!");
    time.setAnimation(anim);
    count.setVisibility(View.VISIBLE);
    cuenta = 0;
    count.setText("0");
} else /* and so on */

Basically you just check if your are in a special interval if not check the next one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM