+ 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?
4 Réponses
+ 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);
}
}
}
+ 14
Two examples using Stream class:
https://code.sololearn.com/canS4v8RpoFD/?ref=app
+ 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);
}
}
}
+ 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.