Java - Skip values in for loop

后端 未结 8 2078
太阳男子
太阳男子 2021-01-07 03:06

I am trying to skip values using a for loop. Something like

for(int i = 32; i <= 255 - but skip 128 to 159; i++) {

    char ascii = (char) i;
    System.         


        
相关标签:
8条回答
  • 2021-01-07 03:36

    Use this at the beginning of your loop:

    for(int i = 32; i < 256; i++) {
        if(i == 128) i = 160;
        //...
    }
    

    This is MUCH better than simply continuing. You don't want to iterate over 128 to 159; you'd be wasting time.

    0 讨论(0)
  • 2021-01-07 03:38

    Here is some code:

    public static void main(String[] args) {
        for(int i = 32; i <= 255; i++) {
            if (i < 128 || i > 159) {
                char ascii = (char) i;
                System.out.println(ascii);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-07 03:39

    Or add the test to the loop like a functional language:

    for(int i = 32; i <= 255; i++) if (i < 128 || i > 159) {
        char ascii = (char) i;
        System.out.println(ascii);
    }
    
    0 讨论(0)
  • 2021-01-07 03:44
    for(int i = 32; i <= 255 - but skip 128 to 159; i++) {
        char ascii = (char) i;
        System.out.println(ascii);
        if(i == 127) {
            i = 160;
        }
    }
    
    0 讨论(0)
  • 2021-01-07 03:46

    You can skip the elements that you do not want, like this:

    for(int i = 32; i <= 255; i++) {
        if (i >= 128 && i <= 159) continue;
        char ascii = (char) i;
        System.out.println(ascii);
    }
    

    or split the loop in two, like this:

    for(int i = 32; i <= 127; i++) {
        char ascii = (char) i;
        System.out.println(ascii);
    }
    for(int i = 160; i <= 256; i++) {
        char ascii = (char) i;
        System.out.println(ascii);
    }
    
    0 讨论(0)
  • 2021-01-07 03:48

    You could add an if statement inside your loop.-

    for(int i = 32; i <= 255; i++) {
        if (i < 128 || i > 159) {
            char ascii = (char) i;
            System.out.println(ascii);
        }
    }
    
    0 讨论(0)
提交回复
热议问题