From 1b7ac954d11c2e613aaf6ade5fc2f912cd5240c6 Mon Sep 17 00:00:00 2001 From: rodolforfq <31481067+rodolforfq@users.noreply.github.com> Date: Fri, 21 Dec 2018 04:23:16 -0400 Subject: [PATCH] Article improvements (#5961) Added 3 methods used to improve the examples on the article. The new methods are simpler to understand for the target audience. --- .../com/baeldung/controlstructures/Loops.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/core-java-lang/src/main/java/com/baeldung/controlstructures/Loops.java b/core-java-lang/src/main/java/com/baeldung/controlstructures/Loops.java index 83f2a27ea7..bb858ffe22 100644 --- a/core-java-lang/src/main/java/com/baeldung/controlstructures/Loops.java +++ b/core-java-lang/src/main/java/com/baeldung/controlstructures/Loops.java @@ -30,6 +30,16 @@ public class Loops { } while (count < 50); } + /** + * Splits a sentence in words, and prints each word in a new line. + * @param sentence Sentence to print as independent words. + */ + public static void printWordByWord(String sentence) { + for (String word : sentence.split(" ")) { + System.out.println(word); + } + } + /** * Prints text an N amount of times. Shows usage of the {@code break} branching statement. * @param textToPrint Text to repeatedly print. @@ -45,6 +55,21 @@ public class Loops { } } + /** + * Prints text an N amount of times, up to 50. Shows usage of the {@code break} branching statement. + * @param textToPrint Text to repeatedly print. + * @param times Amount to times to print received text. If times is higher than 50, textToPrint will only be printed 50 times. + */ + public static void printTextNTimesUpTo50(String textToPrint, int times) { + int counter = 1; + while (counter < 50) { + System.out.println(textToPrint); + if (counter == times) { + break; + } + } + } + /** * Prints an specified amount of even numbers. Shows usage of both {@code break} and {@code continue} branching statements. * @param amountToPrint Amount of even numbers to print. @@ -70,4 +95,29 @@ public class Loops { } } + /** + * Prints an specified amount of even numbers, up to 100. Shows usage of both {@code break} and {@code continue} branching statements. + * @param amountToPrint Amount of even numbers to print. + */ + public static void printEvenNumbersToAMaxOf100(int amountToPrint) { + if (amountToPrint <= 0) { // Invalid input + return; + } + int iterator = 0; + int amountPrinted = 0; + while (amountPrinted < 100) { + if (iterator % 2 == 0) { // Is an even number + System.out.println(iterator); + amountPrinted++; + iterator++; + } else { + iterator++; + continue; // Won't print + } + if (amountPrinted == amountToPrint) { + break; + } + } + } + }