+ 4

Any easy way to skip more than one number?

public class Program { public static void main(String[] args) { for(int x=10; x<=400; x=x+10) { if(x == 30) {continue;} if(x==50){ continue; } System.out.println(x); } } } in this code i have to type if condition everytime I wanna skip any number. is there any easy way to do this?

21st Apr 2018, 6:48 AM
RH Tasin
RH Tasin - avatar
4 ответов
+ 14
my java a bit rusy so it took me a while to write this xD you can use an array and check.if the current value is contained in it. make sure the skip values array is NOT an array of primitives (use Integer, Double, String,....), otherwise it will not work. import java.util.*; public class Program { public static void main(String[] args) { Integer skip[] = {30, 50, 60, 100}; for(int x=10; x<=400; x=x+10) { if(Arrays.asList(skip).contains(x)) { System.out.println("Skip: " + x); continue; } System.out.println(x); } } }
21st Apr 2018, 7:23 AM
Burey
Burey - avatar
+ 14
Two examples using Stream class: https://code.sololearn.com/canS4v8RpoFD/?ref=app
21st Apr 2018, 8:16 AM
Tashi N
Tashi N - avatar
+ 8
You can use a Switch. You only have to specify in each case the numbers you do not want to show and at the end of the sentence. Example: public class Program { public static void main(String[] args) { for(int x=10; x<=400; x=x+10) { switch(x) { case 30: case 50: case 70: continue; } System.out.println(x); } } }
21st Apr 2018, 6:56 AM
Mickel
Mickel - avatar
+ 6
In addition to using a switch you could also use an or || if(x==30 || x==50) continue; This is fine if you only have a few conditions to check for, otherwise a switch may be the better option.
21st Apr 2018, 7:17 AM
ChaoticDawg
ChaoticDawg - avatar