5. Control Flow, Exception Handling, and Assertions
5.1 |
Finding primes using for-loops.
// Filename: ForPrimes.java public class ForPrimes { final static int MAX = 100; public static void main(String[] args) { numbers: for (int num = 1; num < MAX; num++) { int divLim = (int) Math.sqrt(num); for (int div = 2; div <= divLim; div++) if ((num % div) == 0) continue numbers; System.out.println(num); } } } Finding primes using while-loops. // Filename: WhilePrimes.java public class WhilePrimes { final static int MAX = 100; public static void main(String[] args) { int num = 1; numbers: while (num < MAX) { int number = num++; int divLim = (int) Math.sqrt(number); int div = 2; while (div <= divLim) if ((number % div++) == 0) continue numbers; System.out.println(number); ... |
Get Programmer's Guide to Java™ Certification, A: A Comprehensive Primer, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.