Skip to content

Commit 1b7ac95

Browse files
rodolforfqmaibin
authored andcommitted
Article improvements (eugenp#5961)
Added 3 methods used to improve the examples on the article. The new methods are simpler to understand for the target audience.
1 parent 87b23b4 commit 1b7ac95

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

  • core-java-lang/src/main/java/com/baeldung/controlstructures

‎core-java-lang/src/main/java/com/baeldung/controlstructures/Loops.java‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,16 @@ public static void repetitionTo50Examples() {
3030
} while (count < 50);
3131
}
3232

33+
/**
34+
* Splits a sentence in words, and prints each word in a new line.
35+
* @param sentence Sentence to print as independent words.
36+
*/
37+
public static void printWordByWord(String sentence) {
38+
for (String word : sentence.split(" ")) {
39+
System.out.println(word);
40+
}
41+
}
42+
3343
/**
3444
* Prints text an N amount of times. Shows usage of the {@code break} branching statement.
3545
* @param textToPrint Text to repeatedly print.
@@ -45,6 +55,21 @@ public static void printTextNTimes(String textToPrint, int times) {
4555
}
4656
}
4757

58+
/**
59+
* Prints text an N amount of times, up to 50. Shows usage of the {@code break} branching statement.
60+
* @param textToPrint Text to repeatedly print.
61+
* @param times Amount to times to print received text. If times is higher than 50, textToPrint will only be printed 50 times.
62+
*/
63+
public static void printTextNTimesUpTo50(String textToPrint, int times) {
64+
int counter = 1;
65+
while (counter < 50) {
66+
System.out.println(textToPrint);
67+
if (counter == times) {
68+
break;
69+
}
70+
}
71+
}
72+
4873
/**
4974
* Prints an specified amount of even numbers. Shows usage of both {@code break} and {@code continue} branching statements.
5075
* @param amountToPrint Amount of even numbers to print.
@@ -70,4 +95,29 @@ public static void printEvenNumbers(int amountToPrint) {
7095
}
7196
}
7297

98+
/**
99+
* Prints an specified amount of even numbers, up to 100. Shows usage of both {@code break} and {@code continue} branching statements.
100+
* @param amountToPrint Amount of even numbers to print.
101+
*/
102+
public static void printEvenNumbersToAMaxOf100(int amountToPrint) {
103+
if (amountToPrint <= 0) { // Invalid input
104+
return;
105+
}
106+
int iterator = 0;
107+
int amountPrinted = 0;
108+
while (amountPrinted < 100) {
109+
if (iterator % 2 == 0) { // Is an even number
110+
System.out.println(iterator);
111+
amountPrinted++;
112+
iterator++;
113+
} else {
114+
iterator++;
115+
continue; // Won't print
116+
}
117+
if (amountPrinted == amountToPrint) {
118+
break;
119+
}
120+
}
121+
}
122+
73123
}

0 commit comments

Comments
 (0)