<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ondrej Kvasnovsky on Medium]]></title>
        <description><![CDATA[Stories by Ondrej Kvasnovsky on Medium]]></description>
        <link>https://medium.com/@ondrej-kvasnovsky?source=rss-9242585892a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5PY4RizfEebLU88Qw9DDLw@2x.jpeg</url>
            <title>Stories by Ondrej Kvasnovsky on Medium</title>
            <link>https://medium.com/@ondrej-kvasnovsky?source=rss-9242585892a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:06:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ondrej-kvasnovsky/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Java 101 — Lesson 15: Game Logic Functions — Breaking Down Complex Problems]]></title>
            <link>https://ondrej-kvasnovsky.medium.com/java-101-lesson-15-game-logic-functions-breaking-down-complex-problems-8d60b7afc464?source=rss-9242585892a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d60b7afc464</guid>
            <dc:creator><![CDATA[Ondrej Kvasnovsky]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 00:59:36 GMT</pubDate>
            <atom:updated>2025-11-21T04:03:44.586Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 101 — Lesson 15: Game Logic Functions — Breaking Down Complex Problems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cm1c1cDTDzrhqskN8yQt3A.jpeg" /></figure><h3>Grammar (Syntax)</h3><p><strong>Decomposition</strong> means breaking a big problem into smaller, manageable pieces. Instead of writing one giant main() method with 200 lines of tangled code, you split it into small, focused functions.</p><p><strong>Game logic functions</strong> handle the rules and flow of a game:</p><ul><li>Checking if the game is over</li><li>Determining who won</li><li>Displaying scores and menus</li><li>Announcing results</li><li>Managing game state</li></ul><p>The pattern for game logic functions:</p><pre>boolean checkGameState(parameters) {<br>    // Check a condition about the game<br>    // return true or false;<br>}<br><br>void displayGameInfo(parameters) {<br>    // Show information to the player<br>    // No return value needed<br>}</pre><p><strong>Why decompose game logic?</strong></p><ul><li>Each function has ONE clear job</li><li>Easy to test individual pieces</li><li>Easy to understand what code does</li><li>Easy to modify or fix bugs</li><li>Reusable across different games</li></ul><h3>Examples</h3><h4>Step 1: Create your file</h4><p>Create a file called GameLogic.java</p><h4>Step 2: The problem — Messy main() with mixed logic</h4><p>Here’s what NOT to do — everything crammed in main():</p><pre>void main() {<br>    int score1 = 2;<br>    int score2 = 1;<br>    int round = 3;<br>    int winningScore = 3;<br><br>    // Display score (messy!)<br>    IO.println(&quot;========== ROUND &quot; + round + &quot; ==========&quot;);<br>    IO.println(&quot;Player 1: &quot; + score1 + &quot; | Player 2: &quot; + score2);<br>    // Check if game over (messy!)<br>    if (score1 &gt;= winningScore || score2 &gt;= winningScore) {<br>        IO.println(&quot;Game over!&quot;);<br>        // Determine winner (messy!)<br>        if (score1 &gt; score2) {<br>            IO.println(&quot;Player 1 wins!&quot;);<br>        } else {<br>            IO.println(&quot;Player 2 wins!&quot;);<br>        }<br>    }<br>}</pre><p><strong>Problems with this code:</strong></p><ul><li>Everything is mixed together</li><li>Hard to reuse the display logic</li><li>Can’t test “check game over” separately</li><li>Imagine this 10 times longer — impossible to read!</li></ul><p>Let’s fix it by extracting functions.</p><h4>Step 3: Game over checker — Simple boolean function</h4><pre>void main() {<br>    int score1 = 2;<br>    int score2 = 1;<br>    int winningScore = 3;<br><br>    if (isGameOver(score1, score2, winningScore)) {<br>        IO.println(&quot;Game over!&quot;);<br>    } else {<br>        IO.println(&quot;Game continues...&quot;);<br>    }<br>    // Test different scenarios<br>    IO.println(&quot;Is 3-2 game over? &quot; + isGameOver(3, 2, 3));  // true<br>    IO.println(&quot;Is 2-2 game over? &quot; + isGameOver(2, 2, 3));  // false<br>}<br>boolean isGameOver(int score1, int score2, int winningScore) {<br>    return score1 &gt;= winningScore || score2 &gt;= winningScore;<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>isGameOver() checks ONE thing: is game finished?</li><li>Returns true if either player reached winning score</li><li>Clean boolean function — easy to understand</li><li>Can test it with different scores</li><li>Reusable in any game with scores</li></ul><p>Output:</p><pre>Game continues...<br>Is 3-2 game over? true<br>Is 2-2 game over? false</pre><h4>Step 4: Score display — Formatting game state</h4><pre>void main() {<br>    displayScore(1, 2, 1);<br>    displayScore(2, 2, 2);<br>    displayScore(3, 3, 0);<br>}<br><br>void displayScore(int score1, int score2, int round) {<br>    IO.println(&quot;========== ROUND &quot; + round + &quot; ==========&quot;);<br>    IO.println(&quot;Score: Player 1: &quot; + score1 + &quot; | Player 2: &quot; + score2);<br>    IO.println();<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>displayScore() formats and prints the score</li><li>Void function — just displays, doesn’t return anything</li><li>Consistent formatting every time</li><li>Want to change how scores look? Change ONE function!</li></ul><p>Output:</p><pre>========== ROUND 1 ==========<br>Score: Player 1: 1 | Player 2: 2<br>========== ROUND 2 ==========<br>Score: Player 1: 2 | Player 2: 2<br>========== ROUND 3 ==========<br>Score: Player 1: 3 | Player 2: 0</pre><h4>Step 5: Winner announcement — Display logic</h4><pre>void main() {<br>    announceRoundWinner(1, 5, 10);  // Player 1 wins<br>    announceRoundWinner(2, 8, 3);   // Player 2 wins<br>    announceRoundWinner(0, 7, 7);   // Tie<br>}<br><br>void announceRoundWinner(int winner, int attempts1, int attempts2) {<br>    IO.println(&quot;Player 1: &quot; + attempts1 + &quot; attempts&quot;);<br>    IO.println(&quot;Player 2: &quot; + attempts2 + &quot; attempts&quot;);<br>    if (winner == 1) {<br>        IO.println(&quot;Player 1 wins this round! +1 point\n&quot;);<br>    } else if (winner == 2) {<br>        IO.println(&quot;Player 2 wins this round! +1 point\n&quot;);<br>    } else {<br>        IO.println(&quot;It&#39;s a tie! No points awarded.\n&quot;);<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>Takes winner (1, 2, or 0 for tie) and attempts</li><li>Displays results clearly</li><li>Separates display logic from game logic</li><li>Easy to change announcement format</li></ul><p>Output:</p><pre>Player 1: 5 attempts<br>Player 2: 10 attempts<br>Player 1 wins this round! +1 point<br><br>Player 1: 8 attempts<br>Player 2: 3 attempts<br>Player 2 wins this round! +1 point<br><br>Player 1: 7 attempts<br>Player 2: 7 attempts<br>It&#39;s a tie! No points awarded.</pre><h4>Step 6: Final winner announcement — Championship results</h4><pre>void main() {<br>    announceChampion(3, 1);<br>    IO.println(&quot;---&quot;);<br>    announceChampion(2, 3);<br>}<br><br>void announceChampion(int score1, int score2) {<br>    IO.println(&quot;========== GAME OVER ==========&quot;);<br>    IO.println(&quot;Final Score:&quot;);<br>    IO.println(&quot;Player 1: &quot; + score1 + &quot; rounds won&quot;);<br>    IO.println(&quot;Player 2: &quot; + score2 + &quot; rounds won&quot;);<br>    if (score1 &gt; score2) {<br>        IO.println(&quot;\nPlayer 1 is the CHAMPION!&quot;);<br>    } else {<br>        IO.println(&quot;\nPlayer 2 is the CHAMPION!&quot;);<br>    }<br>    IO.println();<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>announceChampion() shows final results</li><li>Includes celebration message</li><li>Clear separation of display logic</li><li>Makes the game feel polished!</li></ul><p>Output:</p><pre>========== GAME OVER ==========<br>Final Score:<br>Player 1: 3 rounds won<br>Player 2: 1 rounds won<br>Player 1 is the CHAMPION!<br>---<br>========== GAME OVER ==========<br>Final Score:<br>Player 1: 2 rounds won<br>Player 2: 3 rounds won<br>Player 2 is the CHAMPION!</pre><h4>Step 7: Performance grading — Bonus scoring</h4><pre>void main() {<br>    displayGradeReport(3);<br>    displayGradeReport(7);<br>    displayGradeReport(15);<br>    displayGradeReport(25);<br>}<br><br>void displayGradeReport(int attempts) {<br>    String grade = getGrade(attempts);<br>    String comment = getGradeComment(grade);<br>    IO.println(&quot;Attempts: &quot; + attempts);<br>    IO.println(&quot;Grade: &quot; + grade);<br>    IO.println(&quot;Comment: &quot; + comment);<br>    IO.println();<br>}<br>String getGrade(int attempts) {<br>    if (attempts &lt;= 5) {<br>        return &quot;S&quot;;<br>    } else if (attempts &lt;= 10) {<br>        return &quot;A&quot;;<br>    } else if (attempts &lt;= 15) {<br>        return &quot;B&quot;;<br>    } else if (attempts &lt;= 20) {<br>        return &quot;C&quot;;<br>    } else {<br>        return &quot;D&quot;;<br>    }<br>}<br>String getGradeComment(String grade) {<br>    if (grade.equals(&quot;S&quot;)) {<br>        return &quot;Superb! You&#39;re a master!&quot;;<br>    } else if (grade.equals(&quot;A&quot;)) {<br>        return &quot;Excellent work!&quot;;<br>    } else if (grade.equals(&quot;B&quot;)) {<br>        return &quot;Good job!&quot;;<br>    } else if (grade.equals(&quot;C&quot;)) {<br>        return &quot;Not bad, keep practicing.&quot;;<br>    } else {<br>        return &quot;Keep trying, you&#39;ll improve!&quot;;<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>getGrade() converts attempts to letter grade</li><li>getGradeComment() gives encouraging feedback</li><li>displayGradeReport() combines both for complete report</li><li>Three small functions working together!</li></ul><p>Output:</p><pre>Attempts: 3<br>Grade: S<br>Comment: Superb! You&#39;re a master!<br><br>Attempts: 7<br>Grade: A<br>Comment: Excellent work!<br><br>Attempts: 15<br>Grade: B<br>Comment: Good job!<br><br>Attempts: 25<br>Grade: D<br>Comment: Keep trying, you&#39;ll improve!</pre><h4>Step 8: Before and After — See the transformation</h4><p><strong>BEFORE — Messy main():</strong></p><pre>void main() {<br>    int score1 = 0;<br>    int score2 = 0;<br>    int round = 1;<br>    int attempts1 = 5;<br>    int attempts2 = 7;<br><br>    IO.println(&quot;========== ROUND &quot; + round + &quot; ==========&quot;);<br>    IO.println(&quot;Score: Player 1: &quot; + score1 + &quot; | Player 2: &quot; + score2);<br>    IO.println(&quot;Player 1: &quot; + attempts1 + &quot; attempts&quot;);<br>    IO.println(&quot;Player 2: &quot; + attempts2 + &quot; attempts&quot;);<br>    if (attempts1 &lt; attempts2) {<br>        score1++;<br>        IO.println(&quot;Player 1 wins this round! +1 point&quot;);<br>    } else if (attempts2 &lt; attempts1) {<br>        score2++;<br>        IO.println(&quot;Player 2 wins this round! +1 point&quot;);<br>    } else {<br>        IO.println(&quot;It&#39;s a tie! No points awarded.&quot;);<br>    }<br>    if (score1 &gt;= 3 || score2 &gt;= 3) {<br>        IO.println(&quot;========== GAME OVER ==========&quot;);<br>        IO.println(&quot;Final Score:&quot;);<br>        IO.println(&quot;Player 1: &quot; + score1);<br>        IO.println(&quot;Player 2: &quot; + score2);<br>        if (score1 &gt; score2) {<br>            IO.println(&quot;Player 1 wins!&quot;);<br>        } else {<br>            IO.println(&quot;Player 2 wins!&quot;);<br>        }<br>    }<br>}</pre><p><strong>AFTER — Clean with functions:</strong></p><pre>void main() {<br>    int score1 = 0;<br>    int score2 = 0;<br>    int round = 1;<br>    int attempts1 = 5;<br>    int attempts2 = 7;<br><br>    displayScore(score1, score2, round);<br>    int winner = determineWinner(attempts1, attempts2);<br>    announceRoundWinner(winner, attempts1, attempts2);<br>    if (winner == 1) score1++;<br>    if (winner == 2) score2++;<br>    if (isGameOver(score1, score2, 3)) {<br>        announceChampion(score1, score2);<br>    }<br>}</pre><p><strong>See the difference?</strong></p><ul><li>Main is now <strong>readable</strong> — you understand the flow</li><li>Each function has <strong>one job</strong></li><li>Easy to <strong>test</strong> each piece</li><li>Easy to <strong>modify</strong> without breaking things</li><li>This is <strong>professional</strong> code!</li></ul><h4>Step 9: Practice exercise — Build game logic functions</h4><p>Now create these game logic helpers yourself:</p><pre>void main() {<br>    // Test your functions<br>    IO.println(isTie(7, 7));           // Should print: true<br>    IO.println(isTie(5, 8));           // Should print: false<br><br>    displayMenu();  // Should show menu options<br>    IO.println(getWinnerName(1));      // Should print: Player 1<br>    IO.println(getWinnerName(2));      // Should print: Player 2<br>}<br><br>// TODO: Write a helper that checks if two scores are tied<br>// Hint 1: Two scores are tied when they&#39;re equal<br>// Hint 2: Use == to compare integers<br>// Hint 3: Return true if equal, false otherwise<br>boolean isTie(int score1, int score2) {<br>    // Your code here<br>}<br><br>// TODO: Write a helper that displays a game menu<br>// Hint 1: This is a void function (no return)<br>// Hint 2: Print menu options using IO.println()<br>// Hint 3: Include options like &quot;1. Play Round&quot;, &quot;2. View Stats&quot;, &quot;0. Quit&quot;<br>void displayMenu() {<br>    // Your code here<br>}<br><br>// TODO: Write a helper that returns player name from player number<br>// Hint 1: Takes int (1 or 2), returns String<br>// Hint 2: If playerNumber is 1, return &quot;Player 1&quot;<br>// Hint 3: If playerNumber is 2, return &quot;Player 2&quot;<br>// Hint 4: What if neither? Return &quot;Unknown&quot; as default<br>String getWinnerName(int playerNumber) {<br>    // Your code here<br>}</pre><p><strong>Solutions</strong> (try before looking!):</p><pre>boolean isTie(int score1, int score2) {<br>    return score1 == score2;<br>}<br><br>void displayMenu() {<br>    IO.println(&quot;=== Game Menu ===&quot;);<br>    IO.println(&quot;1. Play Round&quot;);<br>    IO.println(&quot;2. View Stats&quot;);<br>    IO.println(&quot;3. View Rules&quot;);<br>    IO.println(&quot;0. Quit&quot;);<br>}<br><br>String getWinnerName(int playerNumber) {<br>    if (playerNumber == 1) {<br>        return &quot;Player 1&quot;;<br>    } else if (playerNumber == 2) {<br>        return &quot;Player 2&quot;;<br>    } else {<br>        return &quot;Unknown&quot;;<br>    }<br>}</pre><h4>Try to find what is wrong in the following code</h4><pre>// 1<br>boolean isGameOver(int score1, int score2, int winningScore) {<br>    if (score1 &gt;= winningScore) {<br>        return true;<br>    }<br>    if (score2 &gt;= winningScore) {<br>        return true;<br>    }<br>    return false;<br>}<br><br>// 2<br>void announceWinner(int score1, int score2) {<br>    IO.println(&quot;Player 1: &quot; + score1);<br>    IO.println(&quot;Player 2: &quot; + score2);<br>    if (score1 &gt; score2) {<br>        return &quot;Player 1 wins!&quot;;<br>    } else {<br>        return &quot;Player 2 wins!&quot;;<br>    }<br>}<br><br>// 3<br>String getGrade(int attempts) {<br>    if (attempts &lt;= 5) {<br>        return &quot;S&quot;;<br>    } else if (attempts &lt;= 10) {<br>        return &quot;A&quot;;<br>    } else if (attempts &lt;= 15) {<br>        return &quot;B&quot;;<br>    }<br>    // Missing something?<br>}<br><br>// 4<br>void displayScore(int score1, int score2, int round) {<br>    String message = &quot;Round &quot; + round + &quot;: P1=&quot; + score1 + &quot;, P2=&quot; + score2;<br>    return message;<br>}</pre><p><strong>Answers:</strong></p><ol><li><strong>Unnecessarily verbose</strong> — This works but is too wordy. Since we’re checking two conditions that both return true, we can simplify to: return score1 &gt;= winningScore || score2 &gt;= winningScore;. One line instead of six!</li><li><strong>Wrong return type</strong> — Function is declared as void (no return) but tries to return Strings. Either change to String announceWinner(...) and return the message, OR keep it void and use IO.println() instead of return.</li><li><strong>Missing return for some paths</strong> — If attempts is greater than 15 (like 20), nothing is returned! Java requires ALL paths to return a value. Add else { return &quot;D&quot;; } or a final return &quot;D&quot;; after the if-else chain.</li><li><strong>Void function trying to return</strong> — Function is void but tries to return a String. Either change to String displayScore(...) if you want to return the message, OR remove the return and just use IO.println(message); to display it.</li></ol><h3>Why Is It Important</h3><p><strong>Decomposition makes code readable.</strong> When someone reads your main(), they should understand the program flow in seconds. Functions with clear names act like a table of contents for your code.</p><p><strong>Small functions are easy to test.</strong> You can test isGameOver() with 10 different scores in isolation. If it works by itself, it works everywhere. Testing one giant function? Nightmare.</p><p><strong>Functions prevent bugs.</strong> When display logic is in ONE place (displayScore()), you can&#39;t accidentally format scores differently in different parts of your program. Consistency = fewer bugs.</p><p><strong>Changes are localized.</strong> Want to change how winners are announced? Update ONE function (announceWinner()). Without functions, you&#39;d hunt through hundreds of lines finding every place that announces winners.</p><p><strong>Functions enable reuse.</strong> Write determineWinner() for a guessing game. Later, use it in a quiz game, a racing game, any competitive game. Don&#39;t rewrite — reuse!</p><p><strong>Professional code is decomposed.</strong> Real software has thousands of functions. Each does one thing well. Learning to decompose now prepares you for real-world programming.</p><p><strong>This is how pros think.</strong> When experienced programmers see a problem, they immediately think: “What are the pieces?” Then they write a function for each piece. You’re learning to think like a professional!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d60b7afc464" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 101 — Lesson 14: Input Validation & Robustness]]></title>
            <link>https://ondrej-kvasnovsky.medium.com/java-101-lesson-14-input-validation-robustness-908331a56f3d?source=rss-9242585892a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/908331a56f3d</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ondrej Kvasnovsky]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 21:19:51 GMT</pubDate>
            <atom:updated>2025-11-21T01:00:11.668Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 101 — Lesson 14: Input Validation &amp; Robustness</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iz_7osU1ytFTVBhAK5Igng.jpeg" /></figure><h3>Grammar (Syntax)</h3><p><strong>Input validation</strong> means checking if user input is correct before using it. Users make mistakes — they type letters when you want numbers, enter 500 when the range is 1–100, or accidentally hit Enter without typing anything.</p><p><strong>Robust programs</strong> handle bad input gracefully instead of crashing or behaving strangely.</p><p>The pattern for input validation:</p><pre>while (input is not valid) {<br>    Show error message<br>    Ask again<br>}<br>// Now input is definitely valid!</pre><p><strong>Why validate input?</strong></p><ul><li>Prevent crashes (typing “hello” when program expects a number)</li><li>Enforce rules (only accept 1–100, not 500)</li><li>Improve user experience (helpful error messages)</li><li>Make your program professional and reliable</li></ul><h3>Examples</h3><h4>Step 1: Create your file</h4><p>Create a file called InputValidation.java</p><h4>Step 2: The problem — Programs crash with bad input</h4><p>First, let’s see what happens WITHOUT validation:</p><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    IO.println(&quot;Enter a number between 1 and 10:&quot;);<br>    int number = scanner.nextInt();<br><br>    IO.println(&quot;You entered: &quot; + number);<br>    IO.println(&quot;Doubled: &quot; + (number * 2));<br>}</pre><p><strong>What happens if the user types:</strong></p><ul><li>&quot;hello&quot; → Program crashes! Exception thrown</li><li>500 → Program accepts it, but it&#39;s outside 1-10</li><li>0 → Accepted, but invalid for our range</li></ul><p>This is bad! Professional programs don’t crash. Let’s fix it.</p><h4>Step 3: Basic validation — Keep asking until valid</h4><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    int number = -1;  // Start with invalid value<br>    while (number &lt; 1 || number &gt; 10) {<br>        IO.println(&quot;Enter a number between 1 and 10:&quot;);<br>        number = scanner.nextInt();<br>        if (number &lt; 1 || number &gt; 10) {<br>            IO.println(&quot;Invalid! Must be between 1 and 10.\n&quot;);<br>        }<br>    }<br><br>    IO.println(&quot;Great! You entered: &quot; + number);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>Start with number = -1 (definitely invalid)</li><li>Loop while number is outside range</li><li>If invalid, show error and ask again</li><li>Keep looping until valid input received</li><li>Once loop exits, we KNOW number is valid!</li></ul><p>Output example:</p><pre>Enter a number between 1 and 10:<br>500<br>Invalid! Must be between 1 and 10.<br>Enter a number between 1 and 10:<br>0<br>Invalid! Must be between 1 and 10.<br>Enter a number between 1 and 10:<br>7<br>Great! You entered: 7</pre><h3>Step 4: Using helper functions for cleaner validation</h3><p>Remember isInRange() from Lesson 13? Let&#39;s use it!</p><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    int number = -1;<br>    while (!isInRange(number, 1, 10)) {<br>        IO.println(&quot;Enter a number between 1 and 10:&quot;);<br>        number = scanner.nextInt();<br><br>        if (!isInRange(number, 1, 10)) {<br>            IO.println(&quot;Invalid! Must be between 1 and 10.\n&quot;);<br>        }<br>    }<br>    IO.println(&quot;Great! You entered: &quot; + number);<br>}<br><br>boolean isInRange(int value, int min, int max) {<br>    return value &gt;= min &amp;&amp; value &lt;= max;<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>!isInRange(number, 1, 10) means &quot;NOT in range&quot;</li><li>Much more readable than number &lt; 1 || number &gt; 10</li><li>Easy to change range — just update the numbers!</li><li>Reusable helper function</li></ul><h4>Step 5: Validation helper — Reusable input function</h4><p>Let’s make a helper that handles ALL the validation logic:</p><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    int age = getValidInput(scanner, &quot;Enter your age:&quot;, 1, 120);<br>    IO.println(&quot;Age: &quot; + age);<br><br>    int score = getValidInput(scanner, &quot;Enter test score:&quot;, 0, 100);<br>    IO.println(&quot;Score: &quot; + score);<br><br>    int guess = getValidInput(scanner, &quot;Guess a number:&quot;, 1, 100);<br>    IO.println(&quot;You guessed: &quot; + guess);<br>}<br><br>int getValidInput(Scanner scanner, String prompt, int min, int max) {<br>    int value = min - 1;  // Start with invalid value<br>    while (!isInRange(value, min, max)) {<br>        IO.println(prompt);<br><br>        value = scanner.nextInt();<br>        if (!isInRange(value, min, max)) {<br>            IO.println(&quot;Invalid! Must be between &quot; + min + &quot; and &quot; + max + &quot;.\n&quot;);<br>        }<br>    }<br>    return value;<br>}<br><br>boolean isInRange(int value, int min, int max) {<br>    return value &gt;= min &amp;&amp; value &lt;= max;<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>getValidInput() handles all validation logic</li><li>Takes custom prompt, min, and max</li><li>Returns only when input is valid</li><li>Reuse it everywhere in your program!</li><li>No duplicate validation code</li></ul><p>Output example:</p><pre>Enter your age:<br>200<br>Invalid! Must be between 1 and 120.<br>Enter your age:<br>25<br>Age: 25<br>Enter test score:<br>105<br>Invalid! Must be between 0 and 100.<br>Enter test score:<br>87<br>Score: 87<br>Guess a number:<br>50<br>You guessed: 50</pre><h4>Step 6: Handling non-numeric input safely</h4><p>What if the user types letters instead of numbers? The program crashes! Let’s fix that:</p><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    int number = getIntegerSafely(scanner, &quot;Enter a number:&quot;);<br>    IO.println(&quot;You entered: &quot; + number);<br>}<br><br>int getIntegerSafely(Scanner scanner, String prompt) {<br>    IO.println(prompt);<br>    while (!scanner.hasNextInt()) {<br>        IO.println(&quot;That&#39;s not a number! Try again:&quot;);<br>        scanner.next();  // Clear the invalid input<br>    }<br>    return scanner.nextInt();<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>scanner.hasNextInt() checks if next input is an integer</li><li>If NOT an integer, show error</li><li>scanner.next() clears the bad input from scanner</li><li>Keep asking until they type a valid integer</li><li>No more crashes!</li></ul><p><strong>New concept:</strong> scanner.hasNextInt() returns true if the next input can be read as an integer, false otherwise.</p><p>Output example:</p><pre>Enter a number:<br>hello<br>That&#39;s not a number! Try again:<br>abc<br>That&#39;s not a number! Try again:<br>123<br>You entered: 123</pre><h3>Step 7: Combining safe input with range validation</h3><p>The ultimate validation helper — handles BOTH non-numeric input AND range checking:</p><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br>    int guess = getValidInputSafe(scanner, &quot;Guess (1-100):&quot;, 1, 100);<br>    IO.println(&quot;Valid guess: &quot; + guess);<br>}<br><br>int getValidInputSafe(Scanner scanner, String prompt, int min, int max) {<br>    int value = min - 1;<br>    while (!isInRange(value, min, max)) {<br>        IO.println(prompt);<br><br>        // First, make sure it&#39;s a number<br>        while (!scanner.hasNextInt()) {<br>            IO.println(&quot;That&#39;s not a number! Try again:&quot;);<br>            scanner.next();<br>            IO.println(prompt);<br>        }<br><br>        value = scanner.nextInt();<br>        // Then check if it&#39;s in range<br>        if (!isInRange(value, min, max)) {<br>            IO.println(&quot;Invalid! Must be between &quot; + min + &quot; and &quot; + max + &quot;.\n&quot;);<br>        }<br>    }<br>    return value;<br>}<br><br>boolean isInRange(int value, int min, int max) {<br>    return value &gt;= min &amp;&amp; value &lt;= max;<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>Outer loop: Keep going until value is in range</li><li>Inner loop: Keep going until input is actually a number</li><li>Clear bad input with scanner.next()</li><li>Then validate the range</li><li>Bulletproof validation!</li></ul><p>Output example:</p><pre>Guess (1-100):<br>hello<br>That&#39;s not a number! Try again:<br>Guess (1-100):<br>abc<br>That&#39;s not a number! Try again:<br>Guess (1-100):<br>500<br>Invalid! Must be between 1 and 100.<br>Guess (1-100):<br>-10<br>Invalid! Must be between 1 and 100.<br>Guess (1-100):<br>42<br>Valid guess: 42</pre><h4>Step 8: Practice exercise — Build your validation toolkit</h4><p>Now create these validation helpers yourself:</p><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    // Test your helpers<br>    int positive = getPositiveInt(scanner, &quot;Enter a positive number:&quot;);<br>    IO.println(&quot;Got: &quot; + positive);<br><br>    boolean answer = getYesNo(scanner, &quot;Do you like pizza? (yes/no):&quot;);<br>    IO.println(&quot;Answer: &quot; + answer);<br>}</pre><pre>// TODO: Write a helper that gets a positive integer (&gt; 0)<br>// Hint 1: Similar to getValidInput, but min is always 1<br>// Hint 2: You can use a very large number for max, like 999999<br>// Hint 3: Or check if value &gt; 0 instead of using isInRange<br>int getPositiveInt(Scanner scanner, String prompt) {<br>    // Your code here<br>}</pre><pre>// TODO: Write a helper that gets yes/no answer<br>// Hint 1: Use scanner.next() to read a String<br>// Hint 2: Check if input equals &quot;yes&quot; or &quot;no&quot; (use .equals())<br>// Hint 3: Use .equalsIgnoreCase() to accept &quot;YES&quot;, &quot;Yes&quot;, &quot;yes&quot;<br>// Hint 4: Return true for yes, false for no<br>// Hint 5: Keep looping until user types yes or no<br>boolean getYesNo(Scanner scanner, String prompt) {<br>    // Your code here<br>}<br><br>// Hint 6: You can look at the solution below, but try to understand <br>//         the logic first, then go back to your code and try to write it.</pre><p><strong>Solutions</strong> (try before looking!):</p><pre>int getPositiveInt(Scanner scanner, String prompt) {<br>    int value = 0;<br>    while (value &lt;= 0) {<br>        IO.println(prompt);<br><br>        while (!scanner.hasNextInt()) {<br>            IO.println(&quot;That&#39;s not a number! Try again:&quot;);<br>            scanner.next();<br>            IO.println(prompt);<br>        }<br><br>        value = scanner.nextInt();<br>        if (value &lt;= 0) {<br>            IO.println(&quot;Must be positive (greater than 0)!\n&quot;);<br>        }<br>    }<br>    return value;<br>}<br><br>boolean getYesNo(Scanner scanner, String prompt) {<br>    String answer = scanner.next();<br>    while (!answer.equalsIgnoreCase(&quot;yes&quot;) &amp;&amp; !answer.equalsIgnoreCase(&quot;no&quot;)) {<br>        IO.println(prompt);<br><br>        answer = scanner.next();<br>        if (!answer.equalsIgnoreCase(&quot;yes&quot;) &amp;&amp; !answer.equalsIgnoreCase(&quot;no&quot;)) {<br>            IO.println(&quot;Please type &#39;yes&#39; or &#39;no&#39;!\n&quot;);<br>        }<br>    }<br>    return answer.equalsIgnoreCase(&quot;yes&quot;);<br>}</pre><h3>Try to find what is wrong in the following code</h3><pre>// 1<br>int getValidInput(Scanner scanner, String prompt, int min, int max) {<br>    int value = min - 1;<br><br>    if (!isInRange(value, min, max)) {<br>        IO.println(prompt);<br>        value = scanner.nextInt();<br>    }<br><br>    return value;<br>}</pre><pre>// 2<br>int getAge(Scanner scanner) {<br>    IO.println(&quot;Enter your age:&quot;);<br>    int age = scanner.nextInt();<br><br>    while (age &lt; 0 || age &gt; 120) {<br>        IO.println(&quot;Invalid age!&quot;);<br>    }<br>    return age;<br>}</pre><pre>// 3<br>int getNumber(Scanner scanner) {<br>    int num = 0;<br><br>    while (num == 0) {<br>        IO.println(&quot;Enter a non-zero number:&quot;);<br>        num = scanner.nextInt();<br>    }<br>    return num;<br>}</pre><pre>// 4<br>boolean isInRange(int value, int min, int max) {<br>    if (value &gt;= min &amp;&amp; value &lt;= max) {<br>        return true;<br>    } else {<br>        return false;<br>    }<br>}</pre><p><strong>Answers:</strong></p><ol><li><strong>Missing loop — uses if instead of while</strong> — Uses if instead of while, so it only checks ONCE. If the user enters invalid input, the function still returns that invalid value instead of asking again. Should be while (!isInRange(value, min, max)) { ... } to keep looping until valid input is received.</li><li><strong>Infinite loop</strong> — The while loop checks if age is invalid but never asks for new input! It will print “Invalid age!” forever. Should add age = scanner.nextInt(); inside the loop to get new input.</li><li><strong>Wrong logic</strong> — while (num == 0) means &quot;while num IS zero, keep looping&quot;. But we want to reject zero! Should be while (num == 0) but with validation message, OR better: while (num &gt;= -10 &amp;&amp; num &lt;= 10) if we want non-zero in a range. As written, entering 0 would loop forever without asking again.</li><li><strong>Unnecessarily verbose</strong> — This works but is too wordy. Since value &gt;= min &amp;&amp; value &lt;= max already returns true/false, you can just write: return value &gt;= min &amp;&amp; value &lt;= max;. No need for the if-else!</li></ol><h3>Why Is It Important</h3><p><strong>Users WILL enter bad input.</strong> It’s not a question of if, but when. Someone will type letters, numbers outside the range, or just mash the keyboard. Your program must handle it.</p><p><strong>Validation prevents crashes.</strong> Without checking scanner.hasNextInt(), your program crashes when users type text. Professional software doesn&#39;t crash — it shows helpful error messages.</p><p><strong>Validation enforces rules.</strong> If you’re building a guessing game for 1–100, accepting 500 breaks the game. Validation keeps the program working correctly.</p><p><strong>Good error messages help users.</strong> “Invalid!” is bad. “Must be between 1 and 100” is helpful. Users can fix their mistake and continue.</p><p><strong>Validation helpers reduce code duplication.</strong> Write getValidInput() once, use it everywhere. Your code stays clean and consistent.</p><p><strong>Robust programs feel professional.</strong> When a program handles mistakes gracefully, users trust it. When it crashes on typos, users get frustrated.</p><p><strong>This is defensive programming.</strong> Always assume input could be wrong. Check it. Validate it. Only then use it. This mindset makes you a better programmer.</p><h3>Next</h3><ul><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-15-game-logic-functions-breaking-down-complex-problems-8d60b7afc464?postPublishedType=initial">Java 101 — Lesson 15: Game Logic Functions — Breaking Down Complex Problems</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=908331a56f3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 101 — Lesson 13: Helper Functions — Building Your Toolkit]]></title>
            <link>https://ondrej-kvasnovsky.medium.com/java-101-lesson-13-helper-functions-building-your-toolkit-062510a2b453?source=rss-9242585892a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/062510a2b453</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ondrej Kvasnovsky]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 17:52:09 GMT</pubDate>
            <atom:updated>2025-11-09T22:08:36.856Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 101 — Lesson 13: Helper Functions — Building Your Toolkit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueIZKQBwFxuGTZF1HYTc-Q.jpeg" /></figure><h3>Grammar (Syntax)</h3><p><strong>Helper functions</strong> are small, focused methods that do one specific job really well. They’re called “helpers” because they help your main program by handling specific tasks.</p><p>The pattern for helper functions:</p><pre>returnType functionName(parameters) {<br>    // Do one specific thing<br>    return result;<br>}</pre><p><strong>Characteristics of good helper functions:</strong></p><ul><li>Does ONE thing clearly</li><li>Has a descriptive name that explains what it does</li><li>Takes inputs it needs as parameters</li><li>Returns a useful result</li><li>Can be tested independently</li><li>Can be reused in different places</li></ul><p><strong>Why write helper functions?</strong> Instead of writing all your code in main(), you break it into small pieces. Each piece is easier to:</p><ul><li>Understand (what does it do?)</li><li>Test (does it work correctly?)</li><li>Fix (if there’s a bug)</li><li>Reuse (use it multiple times)</li></ul><h3>Examples</h3><h4><strong>Step 1: Create your file</strong></h4><p>Create a file called HelperFunctions.java</p><h4><strong>Step 2: Range validation helper</strong></h4><p>This helper checks if a number is within a valid range:</p><pre>void main() {<br>    // Test the helper function<br>    IO.println(isInRange(50, 1, 100));    // true<br>    IO.println(isInRange(150, 1, 100));   // false<br>    IO.println(isInRange(0, 1, 100));     // false<br>    IO.println(isInRange(1, 1, 100));     // true<br>    IO.println(isInRange(100, 1, 100));   // true<br>}<br><br>boolean isInRange(int value, int min, int max) {<br>    return value &gt;= min &amp;&amp; value &lt;= max;<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>isInRange() checks if a value is between min and max (inclusive)</li><li>Returns true if in range, false if outside</li><li>Takes 3 parameters: the value to check, minimum, and maximum</li><li>One clear job: validate if number is in range</li></ul><p><strong>Why is this useful?</strong> Instead of writing guess &gt;= 1 &amp;&amp; guess &lt;= 100 everywhere, you write isInRange(guess, 1, 100). More readable and reusable!</p><h4><strong>Step 3: Hint generator helper</strong></h4><p>This helper gives feedback based on a guess:</p><pre>void main() {<br>    int secretNumber = 42;<br><br>    IO.println(giveHint(30, secretNumber)); // Too low!<br>    IO.println(giveHint(50, secretNumber)); // Too high!<br>    IO.println(giveHint(42, secretNumber)); // Correct!<br>}<br><br>String giveHint(int guess, int secret) {<br>    if (guess &lt; secret) {<br>        return &quot;Too low!&quot;;<br>    } else if (guess &gt; secret) {<br>        return &quot;Too high!&quot;;<br>    } else {<br>        return &quot;Correct!&quot;;<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>giveHint() compares guess to secret number</li><li>Returns a String with the appropriate feedback</li><li>Clean separation: this function only generates hints</li><li>You can use it in any guessing game</li></ul><h4><strong>Step 4: Distance calculator helper</strong></h4><p>How close was the guess?</p><pre>void main() {<br>    int secret = 50;<br><br>    IO.println(&quot;Distance from 45: &quot; + getDistance(45, secret));<br>    IO.println(&quot;Distance from 30: &quot; + getDistance(30, secret));<br>    IO.println(&quot;Distance from 70: &quot; + getDistance(70, secret));<br>    IO.println(&quot;Distance from 50: &quot; + getDistance(50, secret));<br>}<br><br>int getDistance(int guess, int secret) {<br>    return Math.abs(guess - secret);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>getDistance() calculates how far off the guess was</li><li>Uses Math.abs() to always get a positive distance</li><li>Returns an int (the distance)</li><li>Useful for “hot/cold” feedback or scoring</li></ul><p>Output:</p><pre>Distance from 45: 5<br>Distance from 30: 20<br>Distance from 70: 20<br>Distance from 50: 0</pre><h4><strong>Step 5: Winner determination helper</strong></h4><p>Who won based on attempts?</p><pre>void main() {<br>  // Test different scenarios<br>  int winner1 = determineWinner(5, 10);<br>  IO.println(&quot;Player1: 5 attempts, Player2: 10 attempts, Winner: &quot; + winner1);<br><br>  int winner2 = determineWinner(8, 3);<br>  IO.println(&quot;Player1: 8 attempts, Player2: 3 attempts, Winner: &quot; + winner2);<br><br>  int winner3 = determineWinner(7, 7);<br>  if (winner3 == 0) {<br>      IO.println(&quot;Player1: 7 attempts, Player2: 7 attempts, It&#39;s a tie!&quot;);<br>  }<br>}<br>int determineWinner(int attempts1, int attempts2) {<br>  if (attempts1 &lt; attempts2) {<br>    return 1;  // Player 1 wins (fewer attempts)<br>  } else if (attempts2 &lt; attempts1) {<br>    return 2;  // Player 2 wins (fewer attempts)<br>  } else {<br>    return 0;  // Tie<br>  }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>determineWinner() compares two scores</li><li>Returns 1 if Player 1 wins, 2 if Player 2 wins, 0 if tie</li><li>Clean logic that can be reused for different number of attempts!</li></ul><p>Output:</p><pre>Player1: 5 attempts, Player2: 10 attempts, Winner: Player 1<br>Player1: 8 attempts, Player2: 3 attempts, Winner: Player 2<br>Player1: 7 attempts, Player2: 7 attempts, It&#39;s a tie!</pre><h4><strong>Step 6: Grade calculator helper</strong></h4><p>Rate performance based on attempts:</p><pre>void main() {<br>    IO.println(&quot;3 attempts: Grade &quot; + getGrade(3));<br>    IO.println(&quot;7 attempts: Grade &quot; + getGrade(7));<br>    IO.println(&quot;12 attempts: Grade &quot; + getGrade(12));<br>    IO.println(&quot;20 attempts: Grade &quot; + getGrade(20));<br>}<br><br>String getGrade(int attempts) {<br>    if (attempts &lt;= 5) {<br>        return &quot;S&quot;;  // Superb<br>    } else if (attempts &lt;= 10) {<br>        return &quot;A&quot;;  // Excellent<br>    } else if (attempts &lt;= 15) {<br>        return &quot;B&quot;;  // Good<br>    } else if (attempts &lt;= 20) {<br>        return &quot;C&quot;;  // Average<br>    } else {<br>        return &quot;D&quot;;  // Needs improvement<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>getGrade() converts attempts into a letter grade</li><li>Fewer attempts means better grade</li><li>Returns a String (the grade letter)</li></ul><p>Output:</p><pre>3 attempts: Grade S<br>7 attempts: Grade A<br>12 attempts: Grade B<br>20 attempts: Grade C</pre><h4><strong>Step 7: Combining helpers — Hot/Cold feedback</strong></h4><p>Let’s use multiple helpers together:</p><pre>void main() {<br>    int secret = 75;<br><br>    testGuess(50, secret);<br>    testGuess(70, secret);<br>    testGuess(78, secret);<br>    testGuess(75, secret);<br>}<br><br>void testGuess(int guess, int secret) {<br>    String hint = giveHint(guess, secret);<br>    int distance = getDistance(guess, secret);<br>    String temperature = getTemperature(distance);<br>    IO.println(&quot;Guess: &quot; + guess + &quot; - &quot; + hint + &quot; (&quot; + temperature + &quot;)&quot;);<br>}<br><br>String giveHint(int guess, int secret) {<br>    if (guess &lt; secret) {<br>        return &quot;Too low!&quot;;<br>    } else if (guess &gt; secret) {<br>        return &quot;Too high!&quot;;<br>    } else {<br>        return &quot;Correct!&quot;;<br>    }<br>}<br><br>int getDistance(int guess, int secret) {<br>    return Math.abs(guess - secret);<br>}<br><br>String getTemperature(int distance) {<br>    if (distance == 0) {<br>        return &quot;Perfect!&quot;;<br>    } else if (distance &lt;= 5) {<br>        return &quot;Burning hot!&quot;;<br>    } else if (distance &lt;= 10) {<br>        return &quot;Hot&quot;;<br>    } else if (distance &lt;= 20) {<br>        return &quot;Warm&quot;;<br>    } else if (distance &lt;= 30) {<br>        return &quot;Cold&quot;;<br>    } else {<br>        return &quot;Freezing!&quot;;<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>testGuess() uses three helper functions</li><li>Each helper does one job</li><li>Combined together, they create rich feedback</li><li>If you need to change how temperature works, you only change getTemperature()</li><li>This is the power of helper functions!</li></ul><p>Output:</p><pre>Guess: 50 - Too low! (Warm)<br>Guess: 70 - Too low! (Hot)<br>Guess: 78 - Too high! (Burning hot!)<br>Guess: 75 - Correct! (Perfect!)</pre><h4><strong>Step 8: Practice exercise — Complete these helpers</strong></h4><p>Now practice writing helper functions yourself! Type this code and fill in the missing parts:</p><pre>void main() {<br>    // Test your helpers<br>    IO.println(isEven(10));           // Should print: true<br>    IO.println(isEven(7));            // Should print: false<br><br>    IO.println(getAbsoluteDiff(10, 3));   // Should print: 7<br>    IO.println(getAbsoluteDiff(3, 10));   // Should print: 7<br><br>    IO.println(isWinner(5, 3));       // Should print: true (5 wins is &gt;= 3)<br>    IO.println(isWinner(2, 3));       // Should print: false<br>}</pre><pre>// TODO: Write a helper that checks if a number is even<br>// Hint 1: Use the modulo operator % from Lesson 9<br>// Hint 2: <br>//   Imagine you have 7 cookies and want to share them <br>//   equally among 3 friends. Each friend gets 2 cookies, <br>//   and 1 cookie is left over. <br>//   That leftover cookie is called the remainder.<br>//   In Java, you&#39;d write this as:<br>//     7 % 3 - and the answer is 1, because 1 cookie is left.<br>// Hint 3: 10 % 2 returns 0<br>// Hint 4: 11 % 2 returns 1<br>boolean isEven(int number) {<br>    // Your code here<br>}</pre><pre>// TODO: Write a helper that gets the absolute difference between two numbers<br>// Hint 1: Use Math.abs() from Lesson 10<br>// Hint 2: getAbsoluteDiff(1, 10) returns 9<br>// Hint 3: getAbsoluteDiff(2, 10) returns 8<br>// Hint 4: getAbsoluteDiff(10, 2) returns 8<br>int getAbsoluteDiff(int a, int b) {<br>    // Your code here<br>}</pre><pre>// TODO: Write a helper that checks if a player has won<br>boolean isWinner(int score, int winningScore) {<br>    // Your code here<br>}</pre><p><strong>Solutions</strong> (try before looking!):</p><pre>boolean isEven(int number) {<br>    return number % 2 == 0;<br>}<br><br>int getAbsoluteDiff(int a, int b) {<br>    return Math.abs(a - b);<br>}<br><br>boolean isWinner(int score, int winningScore) {<br>    return score &gt;= winningScore;<br>}</pre><h3>Try to find what is wrong in the following code</h3><pre>// 1<br>boolean isPositive(int number) {<br>    if (number &gt; 0) {<br>        IO.println(&quot;It&#39;s positive!&quot;);<br>        return true;<br>    } else {<br>        IO.println(&quot;It&#39;s not positive!&quot;);<br>        return false;<br>    }<br>}</pre><pre>// 2<br>String getLevel(int score) {<br>    if (score &gt;= 100) {<br>        return &quot;Expert&quot;;<br>    } else if (score &gt;= 50) {<br>        return &quot;Intermediate&quot;;<br>    }<br>    // Forgot something?<br>}</pre><pre>// 3<br>int calculateScore(int correct, int total) {<br>    int percentage = (correct * 100) / total;<br>    IO.println(&quot;Your score: &quot; + percentage + &quot;%&quot;);<br>    return percentage;<br>}</pre><pre>// 4<br>boolean isInValidRange(int value, int min, int max) {<br>    return value &gt;= min || value &lt;= max;<br>}</pre><p><strong>Answers:</strong></p><ol><li><strong>Helper function doing too much</strong> — A good helper should do ONE thing. This function checks if positive (good) but ALSO prints messages (not good). Helper functions should return values, let the caller decide what to print. Remove the IO.println statements.</li><li><strong>Missing return statement</strong> — If score is less than 50, nothing is returned! Should add else { return &quot;Beginner&quot;; } or add a final return &quot;Beginner&quot;; after the if-else chain.</li><li><strong>Helper function with side effects</strong> — This function prints AND returns. Helper functions should typically just calculate and return. The printing should happen in the code that calls this function, not inside it. Remove the IO.println line.</li><li><strong>Wrong logical operator</strong> — Using OR (||) instead of AND (&amp;&amp;). This returns true for almost everything! For example, isInValidRange(200, 1, 100) returns true because 200 &lt;= 100 is false but 200 &gt;= 1 is true. Should be value &gt;= min &amp;&amp; value &lt;= max.</li></ol><h3>Why Is It Important</h3><p><strong>Helper functions make your code readable.</strong> Compare these two:</p><ul><li>if (score &gt;= winningScore) - what does this mean?</li><li>if (isWinner(score, winningScore)) - crystal clear!</li></ul><p>The second reads like English. Helper functions make code self-documenting.</p><p><strong>You can test each piece independently.</strong> Write isInRange(), test it with 10 different values. If it works alone, it works everywhere. This makes finding bugs much easier.</p><p><strong>Change once, fix everywhere.</strong> If you want to change how hints work, you change ONE function (giveHint). Every place that uses it automatically gets the update.</p><p><strong>Reuse across projects.</strong> Once you write isInRange(), you can use it in ANY program that needs range validation. Build your toolkit of reliable helpers!</p><p><strong>Reduces complexity in main().</strong> Instead of 200 lines of tangled code in main(), you have a clean main that calls well-named helpers. Much easier to understand!</p><p><strong>Professional programmers think in functions.</strong> When pros see a problem, they think: “What small functions do I need?” Then they write and test each one. Finally, they combine them. You’re learning to think like a pro!</p><h3>Next</h3><ul><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-14-input-validation-robustness-908331a56f3d">Java 101 — Lesson 14: Input Validation &amp; Robustness</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=062510a2b453" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching Coding: Making Learning Less Painful]]></title>
            <link>https://ondrej-kvasnovsky.medium.com/teaching-coding-making-learning-less-painful-a9a5755517b4?source=rss-9242585892a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9a5755517b4</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Ondrej Kvasnovsky]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 16:45:36 GMT</pubDate>
            <atom:updated>2025-11-28T16:18:04.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4O-FD_vIJeOgXlWIci3Qg.jpeg" /></figure><h3>The problem</h3><ul><li>Many technical books — even those meant for beginners — focus on <em>completeness</em> over <em>clarity</em>. They try to cover every detail from the start, rather than guiding learners through a gradual process.</li><li>But learning a completely new concept, especially in programming, <strong>hurts</strong>. The mind struggles to process unfamiliar symbols, logic, and abstract rules all at once. Still, there are ways to make this process <em>less painful</em> and much more effective.</li><li>How do we best learn a new concept?</li><li>How do we turn understanding</li></ul><h3>Pedagogical foundations</h3><h4>1. Graduated Scaffolding (Wood, Bruner, Ross 1976):</h4><p>Start with <strong>maximum support</strong>, and then <strong>gradually remove it</strong> as the learner gains confidence.<br>Each lesson should take away a bit of that scaffolding until the learner can stand — and code — independently.</p><blockquote>Think of it like teaching someone to ride a bike: first, training wheels; then, a hand on the seat; finally, balance on their own.</blockquote><h4>2. Deliberate Practice (Ericsson):</h4><p>Don’t try to master “coding” as a single giant skill. Instead, <strong>focus on sub-skills</strong> — functions, validation, logic, loops, etc.</p><p>Each lesson should:</p><ul><li>Target one skill.</li><li>Provide <strong>immediate feedback</strong>.</li><li>Encourage <strong>mastery</strong> before moving on.</li></ul><blockquote>It’s like practicing scales before performing a song. Each repetition builds precision.</blockquote><h4>3. Cognitive Load Theory (Sweller):</h4><p>New learners can easily get overwhelmed — not by difficulty, but by <em>too much, too soon</em>.</p><p>To reduce cognitive load:</p><ul><li>Introduce only one new concept at a time.</li><li>Revisit and reinforce what was just learned.</li><li>Avoid unnecessary jargon or distractions.</li></ul><blockquote>This way, learners don’t burn out trying to juggle syntax, logic, and new mental models all at once.</blockquote><h4>4. Constructivism (Piaget)</h4><p>People learn best when they <strong>build</strong> their own understanding — not when they passively consume information.</p><blockquote><em>Students learn by </em>doing<em>, not just </em>seeing<em>.</em></blockquote><p>Each step should invite learners to experiment, break things, and fix them again. That’s where understanding deepens.</p><h4>5. The “I Do, We Do, You Do” Model</h4><ul><li>I do — Instructor demonstrates the concept — “Here is how to write a function”</li><li>We do — Instructor and student code together — “Let’s write a function together”</li><li>You do with help — Guided practice — “Try making a function that adds two numbers — I will help if you get stuck.”</li><li>You do alone — Independent project — “Build a small calculator app on your own”</li></ul><p>Each stage removes a bit of support, until full independence is reached.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9a5755517b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 101 — Lesson 12: Project — Quiz Game]]></title>
            <link>https://ondrej-kvasnovsky.medium.com/java-101-lesson-12-project-quiz-game-cdbfc5ea2668?source=rss-9242585892a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdbfc5ea2668</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ondrej Kvasnovsky]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 20:34:12 GMT</pubDate>
            <atom:updated>2025-11-09T17:53:02.128Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 101 — Lesson 12: Project — Quiz Game</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIGhzjFaQiGmutyAv-nvrQ.png" /></figure><h3>Project Goal</h3><p>Build a quiz game that asks questions, checks answers, and tracks the score. This project practices:</p><ul><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-8-arrays-storing-multiple-values-200df7c6c8c7">Arrays (Lesson 8)</a></li><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-4-loops-52c556a937d1">Loops (Lesson 4)</a></li><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-7-user-input-making-interactive-programs-a4f7a313b2c9">User input (Lesson 7)</a></li><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-6-conditionals-making-decisions-01d1359b3fd3">Conditionals (Lesson 6)</a></li><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-5-strings-working-with-text-352db6f8b156">String comparison (Lesson 5)</a></li></ul><h3>Planning the Project</h3><h4><strong>What the program needs to do:</strong></h4><ol><li>Store questions and correct answers</li><li>Ask each question</li><li>Get user’s answer</li><li>Check if correct</li><li>Track score</li><li>Show final results</li></ol><h4><strong>Data we’ll need:</strong></h4><ul><li>Array of questions</li><li>Array of answers</li><li>Score counter</li><li>Loop through all questions</li></ul><h4><strong>Methods we’ll need:</strong></h4><ul><li>askQuestion(String question) → gets user’s answer</li><li>checkAnswer(String userAnswer, String correctAnswer) → returns boolean</li><li>displayResults(int score, int total) → shows final score</li><li>main() → runs the quiz</li></ul><h3>Complete Code</h3><h4><strong>Step 1: Create your file</strong></h4><p>Create a file called QuizGame.java</p><h4><strong>Step 2: Write the complete program</strong></h4><pre>void main() {<br>    IO.println(&quot;=== Java Knowledge Quiz ===\n&quot;);<br><br>    // Questions array<br>    String[] questions = {<br>        &quot;What type stores whole numbers? (int/String/boolean)&quot;,<br>        &quot;Which compares string content? (.equals()/==/compare)&quot;,<br>        &quot;Array indexes start at? (0/1/2)&quot;,<br>        &quot;What does void mean? (no return/error/stop)&quot;,<br>        &quot;Loop that needs condition? (while/array/class)&quot;<br>    };<br><br>    // Correct answers array (parallel to questions)<br>    String[] answers = {<br>        &quot;int&quot;,<br>        &quot;.equals()&quot;,<br>        &quot;0&quot;,<br>        &quot;no return&quot;,<br>        &quot;while&quot;<br>    };<br>    int score = 0;<br><br>    // Ask each question<br>    for (int i = 0; i &lt; questions.length; i++) {<br>        IO.println(&quot;Question &quot; + (i + 1) + &quot; of &quot; + questions.length);<br>        String userAnswer = askQuestion(questions[i]);<br><br>        boolean correct = checkAnswer(userAnswer, answers[i]);<br><br>        if (correct) {<br>            IO.println(&quot;✓ Correct!\n&quot;);<br>            score++;<br>        } else {<br>            IO.println(&quot;✗ Wrong! The answer is: &quot; + answers[i] + &quot;\n&quot;);<br>        }<br>    }<br><br>    displayResults(score, questions.length);<br>}<br><br>String askQuestion(String question) {<br>    IO.println(question);<br>    IO.println(&quot;Your answer:&quot;);<br>    return IO.readln();<br>}<br><br>boolean checkAnswer(String userAnswer, String correctAnswer) {<br>    return userAnswer.equalsIgnoreCase(correctAnswer);<br>}<br><br>void displayResults(int score, int total) {<br>    IO.println(&quot;=== Quiz Complete! ===&quot;);<br>    IO.println(&quot;Score: &quot; + score + &quot; / &quot; + total);<br><br>    double percentage = (score * 100.0) / total;<br>    IO.println(&quot;Percentage: &quot; + percentage + &quot;%&quot;);<br><br>    if (percentage &gt;= 90) {<br>        IO.println(&quot;Grade: A - Excellent!&quot;);<br>    } else if (percentage &gt;= 80) {<br>        IO.println(&quot;Grade: B - Good job!&quot;);<br>    } else if (percentage &gt;= 70) {<br>        IO.println(&quot;Grade: C - Not bad&quot;);<br>    } else if (percentage &gt;= 60) {<br>        IO.println(&quot;Grade: D - Keep studying&quot;);<br>    } else {<br>        IO.println(&quot;Grade: F - Review the lessons!&quot;);<br>    }<br>}</pre><h3>How it works</h3><p>Think about how we’re storing quiz data. Each question has a matching correct answer. We could write them like this:</p><ul><li>Question 1: “What type stores whole numbers?” → Answer: “int”</li><li>Question 2: “Which compares string content?” → Answer: “.equals()”</li></ul><p>In our program, we split this into TWO separate arrays — one for questions, one for answers. The trick is: we keep them “in sync” by using the <strong>same index</strong> for related items.</p><pre>questions[0] → &quot;What type stores whole numbers?&quot;<br>answers[0]   → &quot;int&quot;<br><br>questions[1] → &quot;Which compares string content?&quot;<br>answers[1]   → &quot;.equals()&quot;</pre><p>These are called <a href="https://en.wikipedia.org/wiki/Parallel_array"><strong>parallel arrays</strong></a> because they run alongside each other. When we loop through with index i, we can grab the question from questions[i] and its matching answer from answers[i]. They stay connected through their shared index.</p><h3>Challenges to Try</h3><p>Now practice what you learned by adding these features:</p><h4><strong>1. Expand the quiz to 10 questions</strong></h4><p>Add 5 more Java questions to make your quiz more comprehensive. Here are some ideas:</p><ul><li>“What loop goes a specific number of times? (for/while/if)”</li><li>“What keyword creates an object? (new/make/create)”</li><li>“What stores true or false? (boolean/bit/flag)”</li><li>“What’s the first index in arrays? (0/1/-1)”</li><li>“What joins strings together? (+/&amp;/.)”</li></ul><p>Don’t forget to:</p><ul><li>Add questions to the questions[] array</li><li>Add matching answers to the answers[] array</li><li>Keep questions and answers in the same order (parallel arrays!)</li></ul><h4><strong>2. Store the user’s answers in an array</strong></h4><p>Create a new array to remember what the user typed for each question:</p><pre>String[] userAnswers = new String[questions.length];<br><br>// Inside your loop, after getting the answer:<br>userAnswers[i] = userAnswer;</pre><p>Then at the end, show a review with three columns:</p><pre>IO.println(&quot;\n=== Full Review ===&quot;);<br>for (int i = 0; i &lt; questions.length; i++) {<br>    IO.println(&quot;Q: &quot; + questions[i]);<br>    IO.println(&quot;Your answer: &quot; + userAnswers[i]);<br>    IO.println(&quot;Correct answer: &quot; + answers[i]);<br>    IO.println();<br>}</pre><h4><strong>3. Add multiple choice options</strong></h4><p>Instead of typing full answers like “int” or “.equals()”, let users just type a letter (A, B, or C). This makes the quiz easier and faster.</p><p><strong>What needs to change:</strong></p><p>Right now your quiz works like this:</p><ul><li>Question: “What type stores whole numbers?”</li><li>User types: “int”</li><li>You check if “int” equals “int”</li></ul><p>With multiple choice, it will work like this:</p><ul><li>Question: “What type stores whole numbers?”</li><li>Options: “A) int B) String C) boolean”</li><li>User types: “A”</li><li>You check if “A” equals “A”</li></ul><p><strong>Step 1: Create an options array</strong></p><p>Add a third parallel array to store the choices for each question:</p><pre>String[] questions = {<br>    &quot;What type stores whole numbers?&quot;,<br>    &quot;Which compares string content?&quot;,<br>    &quot;Array indexes start at?&quot;<br>};<br><br>String[] options = {<br>    &quot;A) int  B) String  C) boolean&quot;,<br>    &quot;A) ==  B) .equals()  C) compare&quot;,<br>    &quot;A) 1  B) 2  C) 0&quot;<br>};<br><br>// Now answers are letters, not full words!<br>String[] answers = {<br>    &quot;A&quot;,  // int is correct<br>    &quot;B&quot;,  // .equals() is correct<br>    &quot;C&quot;   // 0 is correct<br>};</pre><blockquote>Notice: All three arrays have the <strong>same length</strong> and use the <strong>same index</strong> for related data.</blockquote><p><strong>Step 2: Update the askQuestion() method</strong></p><p>Your method needs to accept TWO parameters now — the question AND the options:</p><pre>String askQuestion(String question, String options) {<br>    IO.println(question);<br>    IO.println(options);  // Show the choices<br>    IO.println(&quot;Your answer (A/B/C):&quot;);<br>    return IO.readln();<br>}</pre><p><strong>Step 3: Update the main loop</strong></p><p>When calling askQuestion(), pass BOTH the question and options:</p><pre>for (int i = 0; i &lt; questions.length; i++) {<br>    IO.println(&quot;Question &quot; + (i + 1) + &quot; of &quot; + questions.length);<br>    String userAnswer = askQuestion(questions[i], options[i]);  // Pass both!<br>  <br>    boolean correct = checkAnswer(userAnswer, answers[i]);<br>    // ... rest of your code<br>}</pre><p>What it looks like when running:</p><pre>Question 1 of 3<br>What type stores whole numbers?<br>A) int  B) String  C) boolean<br>Your answer (A/B/C):<br>A<br>✓ Correct!</pre><p><strong>Tip:</strong> Your checkAnswer() method using equalsIgnoreCase() already handles this perfectly - it will accept &quot;a&quot; or &quot;A&quot; as correct!</p><h4><strong>4. Show results only for wrong answers</strong></h4><p>Right now, the quiz shows feedback after each question. What if you wanted to wait until the end and only show the questions they got wrong? This helps students review their mistakes all at once.</p><p><strong>The challenge:</strong> How do you remember which questions were answered incorrectly?</p><p><strong>The solution:</strong> Use a third parallel array to track results!</p><p><strong>Step 1: Add a results array</strong></p><p>Create a boolean array to remember which questions were correct (true) or wrong (false):</p><pre>String[] questions = { /* your questions */ };<br>String[] answers = { /* your answers */ };<br>boolean[] results = new boolean[questions.length];  // NEW: Track each result<br>int score = 0;</pre><p><strong>New concept — Block comments:</strong> Notice the /* */ syntax? This is a <strong>block comment</strong> (also called a multi-line comment). It works just like // comments, but instead of ending at the line, it can span multiple lines or be placed inside code:</p><ul><li>// comment - everything after // on that line is ignored</li><li>/* */ comment - everything between /* and */ is ignored</li></ul><p><strong>Step 2: Store each result instead of just showing feedback</strong></p><p>In your main loop, save whether the answer was correct:</p><pre>for (int i = 0; i &lt; questions.length; i++) {<br>    IO.println(&quot;Question &quot; + (i + 1) + &quot; of &quot; + questions.length);<br>    String userAnswer = askQuestion(questions[i]);<br><br>    boolean correct = checkAnswer(userAnswer, answers[i]);<br>    results[i] = correct;  // SAVE the result in the array!<br>    if (correct) {<br>        score++;<br>    }<br>}</pre><p>Notice: We removed the immediate feedback (✓ Correct! or ✗ Wrong!). The user won’t know until the end!</p><p><strong>Step 3: Show only wrong answers at the end</strong></p><p>After the quiz is complete, loop through and show only the ones they got wrong:</p><pre>displayResults(score, questions.length);<br><br>IO.println(&quot;\n=== Review Wrong Answers ===&quot;);<br>int wrongCount = 0;<br>for (int i = 0; i &lt; results.length; i++) {<br>    if (!results[i]) {  // If they got it wrong (false)<br>        wrongCount++;<br>        IO.println(wrongCount + &quot;. &quot; + questions[i]);<br>        IO.println(&quot;   Correct answer: &quot; + answers[i]);<br>        IO.println();<br>    }<br>}</pre><p><strong>What it looks like when running:</strong></p><pre><br>Question 1 of 5<br>What type stores whole numbers? (int/String/boolean)<br>Your answer:<br>int<br><br>Question 2 of 5<br>Which compares string content? (.equals()/==/compare)<br>Your answer:<br>==<br><br>Question 3 of 5<br>Array indexes start at? (0/1/2)<br>Your answer:<br>0<br><br>... (continues through all questions)<br><br>=== Quiz Complete! ===<br>Score: 3 / 5<br>Percentage: 60.0%<br>Grade: D - Keep studying<br><br>=== Review Wrong Answers ===<br>1. Which compares string content? (.equals()/==/compare)<br>   Correct answer: .equals()<br><br>2. Loop that needs condition? (while/array/class)<br>   Correct answer: while</pre><h3>Complete version</h3><p>Here is a complete version of the code for you reference: <a href="https://gist.github.com/ondrej-kvasnovsky/263bdc67495dc877f454b23e30064991">https://gist.github.com/ondrej-kvasnovsky/263bdc67495dc877f454b23e30064991</a></p><h3>Test Your Knowledge — Complete Quiz</h3><p>Ready to test everything you’ve learned from Lessons 1–12? Here’s a comprehensive 25-question quiz covering all topics. Copy these arrays into your quiz program and see how well you do!</p><pre>String[] questions = {<br>    &quot;What type stores decimal numbers?&quot;,<br>    &quot;How do you get text from the user?&quot;,<br>    &quot;What does ++ do to a variable?&quot;,<br>    &quot;Which loop should be used if we don&#39;t how many times it would be executed?&quot;,<br>    &quot;What method gets string length?&quot;,<br>    &quot;What symbol starts a single-line comment?&quot;,<br>    &quot;How do you declare an array?&quot;,<br>    &quot;What does a method with void return?&quot;,<br>    &quot;What type stores whole numbers?&quot;,<br>    &quot;What compares two int values for equality?&quot;,<br>    &quot;How do you access array element at index 2?&quot;,<br>    &quot;What prints text to console?&quot;,<br>    &quot;Which loop runs exact number of times?&quot;,<br>    &quot;What&#39;s the default value of boolean?&quot;,<br>    &quot;What is a naming convention for classes?&quot;,<br>    &quot;What keyword creates a new object?&quot;,<br>    &quot;What is an object called after creation?&quot;,<br>    &quot;How do you get array length?&quot;,<br>    &quot;What joins two strings together?&quot;,<br>    &quot;What naming style for variables?&quot;,<br>    &quot;How many parameters this method has: add(int a, int b)?&quot;,<br>    &quot;What does a return statement do?&quot;,<br>    &quot;What is the purpose of main method?&quot;,<br>    &quot;What is a class?&quot;,<br>    &quot;What runs a code if a condition is false?&quot;<br>};<br><br>String[] options = {<br>    &quot;A) int  B) double  C) String&quot;,<br>    &quot;A) IO.readln()  B) IO.println()  C) IO.read()&quot;,<br>    &quot;A) subtracts 1  B) adds 1  C) multiplies by 2&quot;,<br>    &quot;A) for  B) while  C) do-while&quot;,<br>    &quot;A) .length()  B) .size()  C) .count()&quot;,<br>    &quot;A) //  B) /*  C) #&quot;,<br>    &quot;A) int[] arr  B) int arr[]  C) array int&quot;,<br>    &quot;A) nothing  B) true  C) 0&quot;,<br>    &quot;A) double  B) int  C) float&quot;,<br>    &quot;A) =  B) ==  C) .equals()&quot;,<br>    &quot;A) arr.2  B) arr(2)  C) arr[2]&quot;,<br>    &quot;A) System.print()  B) IO.println()  C) IO.write()&quot;,<br>    &quot;A) while  B) for  C) if&quot;,<br>    &quot;A) true  B) false  C) 0&quot;,<br>    &quot;A) UpperCamelCase  B) camelCase  C) snake_case&quot;,<br>    &quot;A) create  B) new  C) make&quot;,<br>    &quot;A) object  B) instance  C) class&quot;,<br>    &quot;A) arr.length  B) arr.size()  C) arr.length()&quot;,<br>    &quot;A) +  B) &amp;  C) .join()&quot;,<br>    &quot;A) UpperCamelCase  B) camelCase  C) snake_case&quot;,<br>    &quot;A) 0  B) 1  C) 2&quot;,<br>    &quot;A) exits method  B) loops back  C) prints value&quot;,<br>    &quot;A) nothing special  B) entry point for our programs&quot;,<br>    &quot;A) a loop  B) a blueprint  C) a method&quot;,<br>    &quot;A) if  B) else  C) while&quot;<br>};<br><br>String[] answers = {<br>    &quot;B&quot;, // double<br>    &quot;A&quot;, // IO.readln()<br>    &quot;B&quot;, // adds 1<br>    &quot;B&quot;, // while<br>    &quot;A&quot;, // .length()<br>    &quot;A&quot;, // //<br>    &quot;A&quot;, // int[] arr<br>    &quot;A&quot;, // nothing<br>    &quot;B&quot;, // int<br>    &quot;B&quot;, // ==<br>    &quot;C&quot;, // arr[2]<br>    &quot;B&quot;, // IO.println()<br>    &quot;B&quot;, // for<br>    &quot;B&quot;, // false<br>    &quot;A&quot;, // UpperCamelCase<br>    &quot;B&quot;, // new<br>    &quot;B&quot;, // instance<br>    &quot;A&quot;, // arr.length<br>    &quot;A&quot;, // +<br>    &quot;B&quot;, // camelCase<br>    &quot;C&quot;, // 2 parameters<br>    &quot;A&quot;, // exits method<br>    &quot;B&quot;, // entry point for our programs<br>    &quot;B&quot;, // a blueprint<br>    &quot;B&quot;  // else<br>};</pre><p><strong>How to use:</strong></p><ol><li>Replace the arrays in your quiz program with these</li><li>Run your quiz and test your knowledge</li><li>Try to get 100% — you’ve learned all of this!</li><li>If you get any wrong, review that lesson</li></ol><p>Give it a try few times until you get this:</p><pre>=== Quiz Complete! ===<br>Score: 25 / 25<br>Percentage: 100.0%<br>Grade: A - Excellent!<br><br>=== Review Wrong Answers ===<br>Perfect! You got everything right!</pre><p>You’re now ready for more complex projects like the final guessing game!</p><h3>Next</h3><ul><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-13-helper-functions-building-your-toolkit-062510a2b453">Java 101 — Lesson 13: Helper Functions — Building Your Toolkit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdbfc5ea2668" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 101 — Lesson 11: Project — Temperature Converter]]></title>
            <link>https://ondrej-kvasnovsky.medium.com/java-101-lesson-11-simple-project-temperature-converter-733a46db6feb?source=rss-9242585892a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/733a46db6feb</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ondrej Kvasnovsky]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 17:40:47 GMT</pubDate>
            <atom:updated>2025-11-02T20:37:33.106Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 101 — Lesson 11: Project — Temperature Converter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3l0yl20H4GidM8gw2zUsw.jpeg" /></figure><h3>Project Goal</h3><p>Build a temperature converter that converts between Celsius, Fahrenheit, and Kelvin. This project practices:</p><ul><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-7-user-input-making-interactive-programs-a4f7a313b2c9">User input (Lesson 7)</a></li><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-9-methods-return-types-and-organization-09c729cb24ef">Methods with return types (Lesson 9)</a></li><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-6-conditionals-making-decisions-01d1359b3fd3">Conditionals (Lesson 6)</a></li><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-4-loops-52c556a937d1">Loops (Lesson 4)</a></li></ul><h3>Planning the Project</h3><p>Before writing code, let’s plan:</p><h4><strong>What the program needs to do:</strong></h4><ol><li>Show a menu of conversion options</li><li>Get user’s choice</li><li>Get temperature value from user</li><li>Convert using the right formula</li><li>Display the result</li><li>Allow multiple conversions (loop until user quits)</li></ol><h4><strong>Methods we’ll need:</strong></h4><ul><li>celsiusToFahrenheit(double c) → returns double</li><li>fahrenheitToCelsius(double f) → returns double</li><li>celsiusToKelvin(double c) → returns double</li><li>kelvinToCelsius(double k) → returns double</li><li>displayMenu() → void (just prints)</li><li>main() → runs the program</li></ul><blockquote><strong>Why separate methods?</strong><br><strong>→ </strong>Each method has ONE job<br><strong>→</strong> Easy to test individual conversions<br><strong>→</strong> Easy to add new conversions<br><strong>→</strong> Code is organized and readable</blockquote><h4><strong>Conversion formulas:</strong></h4><ul><li>Celsius to Fahrenheit: F = (C × 9/5) + 32</li><li>Fahrenheit to Celsius: C = (F - 32) × 5/9</li><li>Celsius to Kelvin: K = C + 273.15</li><li>Kelvin to Celsius: C = K - 273.15</li></ul><h4>How it works — The main loop structure</h4><p>There are the following building blocks for our program:</p><pre>1. Show menu<br>2. Get choice<br>3. If quit → exit<br>4. If valid choice → get temp, convert, display<br>5. If invalid → show error<br>6. Repeat</pre><h4>Example Usage</h4><p>Here is what we are aiming for (with ← showing my explanations so you can better understand what is going):</p><pre>=== Temperature Converter ===<br>1. Celsius to Fahrenheit    ← program displays the options<br>2. Fahrenheit to Celsius<br>3. Celsius to Kelvin<br>4. Kelvin to Celsius<br>0. Quit<br>Enter your choice (0-4):    ← program asks for user&#39;s choice<br>1                           ← you input your choice<br>Enter temperature:          ← program asks for temperature <br>25                          ← you input the temperature<br>25.0°C = 77.0°F             ← program prints the converted temperature</pre><h3>Project Code</h3><h4><strong>Step 1: Create your file</strong></h4><p>Create a file called TemperatureConverter.java</p><h4><strong>Step 2: Write the complete program</strong></h4><p><strong>This is your first complete project!</strong> Up until now, you’ve been learning individual pieces — loops, conditionals, methods, user input. Now you’re putting them ALL together into a real working program.</p><p>The complete code is provided below so you can see how everything fits together. <strong>Don’t just copy-paste it</strong> — type it out line by line.</p><p>This helps you:</p><ul><li>Understand how the methods connect to each other</li><li>See how user input flows through the program</li><li>Build muscle memory for writing Java code</li><li>Spot any parts you don’t fully understand yet</li></ul><p>After you type it and get it working, try making a small change: maybe change the menu text, add a sixth option, or add a message when someone enters 0°C. Making your own modifications is how you truly learn!</p><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br>    IO.println(&quot;=== Temperature Converter ===\n&quot;);<br><br>    boolean keepGoing = true;<br><br>    while (keepGoing) {<br>        displayMenu();<br><br>        IO.println(&quot;Enter your choice (0-4):&quot;);<br>        int choice = scanner.nextInt();<br><br>        if (choice == 0) {<br>            IO.println(&quot;Goodbye!&quot;);<br>            keepGoing = false;<br>        } else if (choice &gt;= 1 &amp;&amp; choice &lt;= 4) {<br>            IO.println(&quot;Enter temperature:&quot;);<br>            double temp = scanner.nextDouble();<br><br>            double result = convertTemperature(choice, temp);<br>            displayResult(choice, temp, result);<br>        } else {<br>            IO.println(&quot;Invalid choice! Please try again.\n&quot;);<br>        }<br>    }<br>}<br><br>void displayMenu() {<br>    IO.println(&quot;1. Celsius to Fahrenheit&quot;);<br>    IO.println(&quot;2. Fahrenheit to Celsius&quot;);<br>    IO.println(&quot;3. Celsius to Kelvin&quot;);<br>    IO.println(&quot;4. Kelvin to Celsius&quot;);<br>    IO.println(&quot;0. Quit&quot;);<br>}<br><br>double convertTemperature(int choice, double temp) {<br>    if (choice == 1) {<br>        return celsiusToFahrenheit(temp);<br>    } else if (choice == 2) {<br>        return fahrenheitToCelsius(temp);<br>    } else if (choice == 3) {<br>        return celsiusToKelvin(temp);<br>    } else if (choice == 4) {<br>        return kelvinToCelsius(temp);<br>    }<br>    return 0.0;<br>}<br><br>double celsiusToFahrenheit(double celsius) {<br>    return (celsius * 9.0 / 5.0) + 32.0;<br>}<br><br>double fahrenheitToCelsius(double fahrenheit) {<br>    return (fahrenheit - 32.0) * 5.0 / 9.0;<br>}<br><br>double celsiusToKelvin(double celsius) {<br>    return celsius + 273.15;<br>}<br><br>double kelvinToCelsius(double kelvin) {<br>    return kelvin - 273.15;<br>}<br><br>void displayResult(int choice, double input, double output) {<br>    String fromUnit;<br>    String toUnit;<br><br>    if (choice == 1) {<br>        fromUnit = &quot;°C&quot;;<br>        toUnit = &quot;°F&quot;;<br>    } else if (choice == 2) {<br>        fromUnit = &quot;°F&quot;;<br>        toUnit = &quot;°C&quot;;<br>    } else if (choice == 3) {<br>        fromUnit = &quot;°C&quot;;<br>        toUnit = &quot;K&quot;;<br>    } else if (choice == 4) {<br>        fromUnit = &quot;K&quot;;<br>        toUnit = &quot;°C&quot;;<br>    } else {<br>        fromUnit = &quot;unknown&quot;;<br>        toUnit = &quot;unknown&quot;;<br>    }<br><br>    IO.println(input + fromUnit + &quot; = &quot; + output + toUnit + &quot;\n&quot;);<br>}</pre><p><strong>New concept:</strong> scanner.nextDouble() reads a decimal number (like scanner.nextInt() but for decimals).</p><h3>Practice Exercises</h3><p>Now practice what you learned by adding these features:</p><h4><strong>1. Add Fahrenheit to Kelvin conversion</strong></h4><p>You’ll need to create a new method fahrenheitToKelvin(). Here&#39;s a hint:</p><ul><li>First convert Fahrenheit to Celsius: C = (F - 32) × 5/9</li><li>Then convert Celsius to Kelvin: K = C + 273.15</li><li>Or combine them: K = (F - 32) × 5/9 + 273.15</li></ul><p>Don’t forget to:</p><ul><li>Add option 6 to your menu</li><li>Update convertTemperature() to handle choice 6</li><li>Update displayResult() to show the correct units</li></ul><h4><strong>2. Add Kelvin to Fahrenheit conversion</strong></h4><p>Create a method kelvinToFahrenheit(). Hint:</p><ul><li>First convert Kelvin to Celsius: C = K - 273.15</li><li>Then convert Celsius to Fahrenheit: F = C × 9/5 + 32</li><li>Or combine them: F = (K - 273.15) × 9/5 + 32</li></ul><p>Add it as option 7 in your menu and update the necessary methods.</p><h4><strong>3. Add input validation (don’t allow Kelvin below 0)</strong></h4><p>Kelvin can’t go below 0 (that’s absolute zero — the coldest possible temperature!). Add a check after getting the temperature from the user:</p><pre>// inside of the while loop, because continue can only be used in a loop<br>// 4 or 6 so temp is checked only when converting from Kelvin<br>if ((choice == 4 || choice == 6) &amp;&amp; temp &lt; 0) {<br>    // System.err.println will make the text red<br>    System.err.println(&quot;Error: Kelvin cannot be below 0!&quot;);<br>    continue;  // Skip this iteration and show menu again<br>}</pre><h4><strong>4. Add rounding to 2 decimal places in output</strong></h4><p>Use DecimalFormat to format numbers nicely:</p><pre>import java.text.DecimalFormat;<br><br>// In your displayResult() method:<br>DecimalFormat df = new DecimalFormat(&quot;#.##&quot;);<br>String formattedOutput = df.format(output);<br><br>IO.println(input + fromUnit + &quot; = &quot; + formattedOutput + toUnit + &quot;\n&quot;);<br><br>// you can also keep the original code, to see the difference<br>IO.println(input + fromUnit + &quot; = &quot; + output + toUnit + &quot;\n&quot;);</pre><p>This will show 25°C = 77°F instead of 25.0°C = 77.0°F.</p><pre>// formatted: <br>45.0°F = 7.22°C<br><br>// not formatted (not rounded to two decimals):<br>45.0°F = 7.222222222222222°C</pre><p>More about DecimalFormat pattern. Look at these examples to observe the pattern how it works.</p><blockquote>The # symbol means a digit will appear only if it&#39;s significant. Otherwise, nothing is displayed in that position.</blockquote><pre>// round to 2 decimal places,<br>// and don&#39;t additional display zeroes<br>DecimalFormat df1 = new DecimalFormat(&quot;#.##&quot;);<br><br>IO.println(df1.format(12.345)); // Output: 12.35<br>IO.println(df1.format(12.301)); // Output: 12.3<br>IO.println(df1.format(12));     // Output: 12<br>IO.println(df1.format(0.789));  // Output: .79<br>IO.println(df1.format(0.0));    // Output: 0<br><br>// round to 3 decimal places<br>DecimalFormat df2 = new DecimalFormat(&quot;0.###&quot;);<br><br>IO.println(df2.format(12));     // Output: 12.00<br>IO.println(df2.format(0.7891)); // Output: 0.789<br><br>// display 0.79 instead of just printing .79<br>// for numbers smaller than 1<br>DecimalFormat df3 = new DecimalFormat(&quot;0.##&quot;);<br><br>IO.println(df3.format(12.301)); // Output: 12.3<br>IO.println(df3.format(0.789));  // Output: 0.79</pre><blockquote>If you want to see how I implemented these features and compare with your implementation, have a look here: <a href="https://gist.github.com/ondrej-kvasnovsky/01819f8cea0584879130f81f9fe34876">https://gist.github.com/ondrej-kvasnovsky/01819f8cea0584879130f81f9fe34876</a></blockquote><h3>What You Learned</h3><p>This project shows how to:</p><ul><li>Break a problem into smaller pieces</li><li>Plan before coding</li><li>Use methods to organize code</li><li>Combine user input, loops, and conditionals</li><li>Build a complete, working program</li></ul><p>You now have all the skills needed to build interactive programs!</p><h3>Next</h3><ul><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-12-project-quiz-game-cdbfc5ea2668">Java 101 — Lesson 12: Project — Quiz Game</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=733a46db6feb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 101 — Lesson 10: Random Numbers & Math]]></title>
            <link>https://ondrej-kvasnovsky.medium.com/java-101-lesson-10-random-numbers-math-f37be0dae36e?source=rss-9242585892a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f37be0dae36e</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ondrej Kvasnovsky]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 16:12:37 GMT</pubDate>
            <atom:updated>2025-11-01T17:42:00.293Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 101 — Lesson 10: Random Numbers &amp; Math</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-swnRLVv3jkTjBkGahp9w.jpeg" /></figure><h3>Grammar (Syntax)</h3><p>Sometimes you want your program to be unpredictable — rolling dice, shuffling cards, picking a random item. Java’s Random class is the best way to generate random numbers.</p><p>First, you need to import and create a Random object:</p><pre>import java.util.Random;<br><br>Random random = new Random();</pre><p>Let’s break it down:</p><ul><li>import java.util.Random; — brings in the Random class (put at the very top of your file)</li><li>Random random — creates a variable to hold a Random object</li><li><strong>new </strong>Random() — creates a new Random number generator</li></ul><p>The pattern for generating a random integer in a range:</p><pre>int randomNumber = random.nextInt(min, max);</pre><p>Let’s break it down:</p><ul><li>random.nextInt(min, max) — generates a random number from min (inclusive) to max (exclusive)</li><li>For example, random.nextInt(1, 101) gives 1 to 100</li><li>For example, random.nextInt(0, 10) gives 0 to 9</li></ul><h3>Examples</h3><h4><strong>Step 1: Create your file</strong></h4><p>Create a file called RandomExamples.java</p><h4><strong>Step 2: Setup — Import and create Random</strong></h4><pre>import java.util.Random;<br><br>void main() {<br>    Random random = new Random();<br>    IO.println(&quot;Random generator ready!&quot;);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>import java.util.Random; at the TOP of the file (before everything)</li><li>Create a Random object once in main</li><li>Use this same random object for all random numbers</li></ul><h4><strong>Step 3: Random integers from 0 to 9</strong></h4><pre>import java.util.Random;<br><br>void main() {<br>    Random random = new Random();<br>    int max = 10;<br>    for (int i = 0; i &lt; 10; i++) {<br>        int randomDigit = random.nextInt(max);<br>        IO.println(&quot;Random digit (0-9): &quot; + randomDigit);<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>random.nextInt(10) generates 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9</li><li>Single parameter means 0 to max-1 (this is shorthand for random.nextInt(0, 10))</li><li>Result: 0 to 9 (10 possible values)</li></ul><p>Output (yours will be different!):</p><pre>Random digit (0-9): 7<br>Random digit (0-9): 2<br>Random digit (0-9): 9<br>Random digit (0-9): 0<br>Random digit (0-9): 5<br>...</pre><h4><strong>Step 4: Simulating a dice roll (1–6)</strong></h4><pre>import java.util.Random;<br><br>void main() {<br>    Random random = new Random();<br>    IO.println(&quot;Rolling dice...&quot;);<br><br>    int die1 = rollDice(random);<br>    int die2 = rollDice(random);<br>    IO.println(&quot;Die 1: &quot; + die1);<br>    IO.println(&quot;Die 2: &quot; + die2);<br>    IO.println(&quot;Total: &quot; + (die1 + die2));<br>}<br><br>int rollDice(Random random) {<br>    return random.nextInt(1, 7);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>random.nextInt(1, 7) gives 1 to 6 (1 inclusive, 7 exclusive)</li><li>We pass the random object to methods so they can use it</li></ul><p>Output (yours will be different!):</p><pre>Rolling dice...<br>Die 1: 4<br>Die 2: 6<br>Total: 10</pre><h4><strong>Step 5: Random number in any range</strong></h4><pre>import java.util.Random;<br><br>void main() {<br>    Random random = new Random();<br><br>    // Random number from 1 to 100<br>    int num1to100 = random.nextInt(1, 101);<br>    IO.println(&quot;Random 1-100: &quot; + num1to100);<br><br>    // Random number from 50 to 150<br>    int num50to150 = random.nextInt(50, 151);<br>    IO.println(&quot;Random 50-150: &quot; + num50to150);<br><br>    // Random number from -10 to 10<br>    int negativeToPositive = random.nextInt(-10, 11);<br>    IO.println(&quot;Random -10 to 10: &quot; + negativeToPositive);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>random.nextInt(1, 101) gives 1 to 100 (max is exclusive, so use 101)</li><li>random.nextInt(50, 151) gives 50 to 150</li><li>random.nextInt(-10, 11) gives -10 to 10 (works with negatives too!)</li></ul><h4><strong>Step 6: Random doubles (decimal numbers)</strong></h4><pre>import java.util.Random;<br><br>void main() {<br>    Random random = new Random();<br>    for (int i = 0; i &lt; 5; i++) {<br>        double randomDouble = random.nextDouble();<br>        IO.println(&quot;Random decimal (0.0-1.0): &quot; + randomDouble);<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>random.nextDouble() generates a decimal from 0.0 to 1.0 (exclusive, so 1.0 is never returned). But you can random.nextDouble(0.5, 10.0) and then it returns values from 0.5 to 10.0.</li><li>Similar to Math.random() but using Random class</li><li>Useful for percentages, probabilities, etc.</li><li>Probability of returning a specific value, like 0, is 1 in 2^54. That is one time in 18,014,398,509,481,984 (eighteen quadrillions) when using random.nextDouble().</li></ul><p>Output (yours will be different!):</p><pre>Random decimal (0.0-1.0): 0.7234567891234567<br>Random decimal (0.0-1.0): 0.23456789012345678<br>Random decimal (0.0-1.0): 0.8901234567890123<br>Random decimal (0.0-1.0): 0.45678901234567890<br>Random decimal (0.0-1.0): 0.12345678901234567</pre><h4><strong>Step 7: Math.min(), Math.max(), Math.abs()</strong></h4><pre>import java.util.Random;<br><br>void main() {<br>    int a = 15;<br>    int b = 27;<br><br>    // Math.max returns the larger number<br>    int bigger = Math.max(a, b);<br>    IO.println(&quot;Bigger: &quot; + bigger);<br><br>    // Math.min returns the smaller number<br>    int smaller = Math.min(a, b);<br>    IO.println(&quot;Smaller: &quot; + smaller);<br><br>    // Math.abs returns absolute value (distance from zero)<br>    int negative = -42;<br>    int positive = Math.abs(negative);<br>    IO.println(&quot;Absolute value of -42: &quot; + positive);<br><br>    int difference = Math.abs(a - b);<br>    IO.println(&quot;Difference between 15 and 27: &quot; + difference);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>Math.max(a, b) returns whichever is larger</li><li>Math.min(a, b) returns whichever is smaller</li><li>Math.abs(n) makes negative numbers positive (absolute value)</li><li>These are useful for comparisons and calculations</li></ul><p>Output:</p><pre>Bigger: 27<br>Smaller: 15<br>Absolute value of -42: 42<br>Difference between 15 and 27: 12</pre><h4><strong>Step 8: Picking a random array element</strong></h4><pre>import java.util.Random;<br><br>void main() {<br>    Random random = new Random();<br>    String[] prizes = {&quot;Car&quot;, &quot;Vacation&quot;, &quot;Cash&quot;, &quot;Phone&quot;, &quot;Nothing&quot;};<br><br>    IO.println(&quot;Spinning the wheel...&quot;);<br>    int randomIndex = random.nextInt(prizes.length);<br><br>    String prize = prizes[randomIndex];<br>    IO.println(&quot;You won: &quot; + prize + &quot;!&quot;);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>prizes.length is 5</li><li>random.nextInt(5) gives 0, 1, 2, 3, or 4</li><li>Use that as the array index to pick random element</li><li>Perfect for random selection from a list</li></ul><p>Output (yours will be different!):</p><pre>Spinning the wheel...<br>You won: Vacation!</pre><h4><strong>Step 9: Simple number guessing game setup</strong></h4><pre>import java.util.Random;<br>import java.util.Scanner;<br><br>void main() {<br>    Random random = new Random();<br>    int secretNumber = random.nextInt(1, 11);<br><br>    IO.println(&quot;I&#39;m thinking of a number between 1 and 10...&quot;);<br>    IO.println(&quot;Take a guess:&quot;);<br><br>    Scanner scanner = new Scanner(System.io);<br>    int guess = scanner.nextInt();<br>    if (guess == secretNumber) {<br>        IO.println(&quot;Correct! The number was &quot; + secretNumber);<br>    } else if (guess &lt; secretNumber) {<br>        IO.println(&quot;Too low! It was &quot; + secretNumber);<br>    } else {<br>        IO.println(&quot;Too high! It was &quot; + secretNumber);<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>random.nextInt(1, 11) generates a secret number from 1 to 10</li><li>Get user’s guess with scanner.nextInt()</li><li>Compare and give feedback</li><li>This is the foundation for a complete guessing game!</li></ul><h3>Try to find what is wrong in the following code</h3><pre>// 1<br>import java.util.Random;<br><br>void main() {<br>    Random random = new Random();<br>    int randomNum = random.nextInt();<br>    if (randomNum &gt;= 1 &amp;&amp; randomNum &lt;= 10) {<br>        IO.println(&quot;Got 1-10: &quot; + randomNum);<br>    }<br>}</pre><pre>// 2<br>import java.util.Random;<br><br>void main() {<br>    Random random = new Random();<br>    // Want random 1-10<br>    int randomNum = random.nextInt(10);<br>    IO.println(randomNum);<br>}</pre><pre>// 3<br>void main() {<br>    Random random = new Random();<br>    int randomNum = random.nextInt(100);<br>    IO.println(randomNum);<br>}</pre><pre>// 4<br>import java.util.Random;<br><br>void main() {<br>    int min = Math.min(5, 10, 15);<br>    IO.println(min);<br>}</pre><p><strong>Answers:</strong></p><ol><li>Wrong approach — nextInt() with no parameter gives ANY integer (can be millions or negative). Should use random.nextInt(1, 11) to get 1-10.</li><li>Off by one — nextInt(10) gives 0-9, not 1-10. Should be random.nextInt(1, 11) to get 1-10.</li><li>Missing import — need import java.util.Random; at the top of the file before using Random class.</li><li>Too many arguments — Math.min() takes exactly 2 values, not 3. Should compare pairs: Math.min(5, Math.min(10, 15)) or just use 5 since it&#39;s clearly smallest.</li></ol><h3>Why Is It Important</h3><p><strong>Random class is the modern way.</strong> Using Random with nextInt() is cleaner and easier to understand than Math.random(). It&#39;s what professional Java programmers use.</p><p><strong>Import teaches you about Java packages.</strong> The import statement shows you how Java organizes code into packages. You&#39;ll use imports all the time as you learn more Java features.</p><p><strong>nextInt(min, max) is straightforward.</strong> random.nextInt(1, 101) clearly means &quot;1 to 100&quot;. No math needed - just specify your range directly!</p><p><strong>Math class provides tested methods.</strong> You could write your own min/max functions, but Math.min(x, y) and Math.max(x, y) are already written, tested, and optimized. Use them!</p><h3>Key Takeaways</h3><ul><li>Import Random class: import java.util.Random; at top of file</li><li>Create Random object: Random random = new Random();</li><li>Random int 0 to n-1: random.nextInt(n)</li><li>Random int with range: random.nextInt(min, max) - min inclusive, max exclusive</li><li>Example: random.nextInt(1, 101) gives 1-100</li><li>Random decimal 0.0–1.0: random.nextDouble()</li><li>Math.max(a, b) returns larger value</li><li>Math.min(a, b) returns smaller value</li><li>Math.abs(n) returns absolute value (makes positive)</li></ul><h3>Next</h3><ul><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-11-simple-project-temperature-converter-733a46db6feb">Java 101 — Lesson 11: Project — Temperature Converter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f37be0dae36e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 101 — Lesson 9: Methods — Return Types and Organization]]></title>
            <link>https://ondrej-kvasnovsky.medium.com/java-101-lesson-9-methods-return-types-and-organization-09c729cb24ef?source=rss-9242585892a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/09c729cb24ef</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ondrej Kvasnovsky]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 04:18:40 GMT</pubDate>
            <atom:updated>2025-11-02T20:53:40.638Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 101 — Lesson 9: Methods — Return Types and Organization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRJFBQSPPNTHXtN_DHZajA.png" /></figure><h3>Grammar (Syntax)</h3><p>In <a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-3-building-a-calculator-acd9b1447d0e">Lesson 3</a>, we learned about methods in classes. Now let’s explore the different types of values methods can return and how to organize your code effectively.</p><p>A <strong>method</strong> is a reusable block of code that performs a specific task. Methods can <strong>return</strong> (give back) different types of values — or no value at all.</p><p>The pattern for a method is:</p><pre>returnType methodName(parameters) {<br>    // code here<br>    return value;<br>}</pre><p>Let’s break down the return types:</p><ul><li><strong>void</strong> — method does something but doesn’t return a value</li><li><strong>int</strong> — method returns a whole number</li><li><strong>String</strong> — method returns text</li><li><strong>boolean</strong> — method returns true or false</li><li><strong>Other types</strong> — methods can return any type (arrays, classes, etc.)</li></ul><p><strong>Important:</strong> If a method’s return type is NOT void, it MUST have a return statement that gives back that type of value.</p><h3>Examples</h3><h4><strong>Step 1: Create your file</strong></h4><p>Create a file called MethodTypes.java</p><h4><strong>Step 2: void methods — do something, return nothing</strong></h4><pre>void main() {<br>    greetUser(&quot;Alice&quot;);<br>    greetUser(&quot;Bob&quot;);<br>    printLine();<br>    IO.println(&quot;End of program&quot;);<br>}<br><br>void greetUser(String name) {<br>    IO.println(&quot;Hello, &quot; + name + &quot;!&quot;);<br>    IO.println(&quot;Welcome to our program.&quot;);<br>}<br><br>void printLine() {<br>    IO.println(&quot;------------------------&quot;);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li><strong>void</strong> means the method doesn’t return anything</li><li>These methods just print stuff — they don’t give back a value</li><li>You call them, they do their job, and that’s it</li><li>No return statement needed (though you can use return; to exit early)</li></ul><p>Output:</p><pre>Hello, Alice!<br>Welcome to our program.<br>Hello, Bob!<br>Welcome to our program.<br>------------------------<br>End of program</pre><h4><strong>Step 3: int methods — return numbers</strong></h4><pre>void main() {<br>    int sum = add(10, 20);<br>    IO.println(&quot;Sum: &quot; + sum);<br><br>    int result = square(7);<br>    IO.println(&quot;7 squared: &quot; + result);<br><br>    // Use return value directly<br>    IO.println(&quot;5 + 3 = &quot; + add(5, 3));<br>}<br><br>int add(int a, int b) {<br>    return a + b;<br>}<br><br>int square(int number) {<br>    return number * number;<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>Methods with int return type MUST return an integer</li><li>The return keyword sends the value back to the caller</li><li>You can store the result in a variable, int result = square(7);, or use it directly: IO.println(“5 + 3 = “ + add(5, 3));</li></ul><p>Output:</p><pre>Sum: 30<br>7 squared: 49<br>5 + 3 = 8</pre><h4><strong>Step 4: String methods — return text</strong></h4><pre>void main() {<br>    String greeting = createGreeting(&quot;Charlie&quot;);<br>    IO.println(greeting);<br><br>    String email = createEmail(&quot;john&quot;, &quot;example.com&quot;);<br>    IO.println(&quot;Email: &quot; + email);<br>}<br><br>String createGreeting(String name) {<br>    return &quot;Hello, &quot; + name + &quot;! Have a great day!&quot;;<br>}<br><br>String createEmail(String username, String domain) {<br>    return username + &quot;@&quot; + domain;<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>Methods with String return type return text</li><li>You can build strings inside the method and return them</li><li>Useful for generating formatted text, messages, etc.</li></ul><p>Output:</p><pre>Hello, Charlie! Have a great day!<br>Email: john@example.com</pre><h4><strong>Step 5: boolean methods — return true or false</strong></h4><pre>void main() {<br>    if (isEven(10)) {<br>        IO.println(&quot;10 is even&quot;);<br>    }<br><br>    if (isAdult(15)) {<br>        IO.println(&quot;You are an adult&quot;);<br>    } else {<br>        IO.println(&quot;You are a minor&quot;);<br>    }<br><br>    boolean validScore = isValidScore(85);<br>    IO.println(&quot;Score valid: &quot; + validScore);<br>}<br><br>boolean isEven(int number) {<br>    return number % 2 == 0;<br>}<br><br>boolean isAdult(int age) {<br>    return age &gt;= 18;<br>}<br><br>boolean isValidScore(int score) {<br>    return score &gt;= 0 &amp;&amp; score &lt;= 100;<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>Methods with boolean return type return true or false</li><li>Perfect for yes/no questions: “is even?”, “is valid?”, “is adult?”</li><li><strong>%</strong> is the modulo operator (remainder after division)</li><li>number % 2 == 0 checks if number is divisible by 2 (even)</li><li>Boolean methods work great with if statements</li></ul><p><strong>New concept:</strong> The % (modulo) operator gives the remainder. 10 % 2 is 0, 11 % 2 is 1.</p><h4><strong>Step 6: Methods calling other methods</strong></h4><pre>void main() {<br>    int[] scores = {85, 92, 78, 88, 95};<br>    printGrade(scores);<br>}<br><br>void printGrade(int[] scoreList) {<br>    int avg = calculateAverage(scoreList);<br>    String grade = getLetterGrade(avg);<br>    IO.println(&quot;Average: &quot; + avg);<br>    IO.println(&quot;Grade: &quot; + grade);<br>}<br><br>int calculateAverage(int[] numbers) {<br>    int sum = 0;<br>    for (int i = 0; i &lt; numbers.length; i++) {<br>        sum = sum + numbers[i];<br>    }<br>    return sum / numbers.length;<br>}<br><br>String getLetterGrade(int average) {<br>    if (average &gt;= 90) {<br>        return &quot;A&quot;;<br>    } else if (average &gt;= 80) {<br>        return &quot;B&quot;;<br>    } else if (average &gt;= 70) {<br>        return &quot;C&quot;;<br>    } else if (average &gt;= 60) {<br>        return &quot;D&quot;;<br>    } else {<br>        return &quot;F&quot;;<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>printGrade calls calculateAverage and getLetterGrade</li><li>Methods can use results from other methods</li><li>Each method has one clear job</li><li>This makes code easier to read, test, and modify</li></ul><h4><strong>Step 7: Practical example — Password validator</strong></h4><pre>void main() {<br>    IO.println(&quot;Enter a password:&quot;);<br>    String password = IO.readln();<br><br>    validatePassword(password);<br>}<br><br>void validatePassword(String pwd) {<br>    boolean longEnough = isLongEnough(pwd);<br>    boolean hasNumber = containsNumber(pwd);<br>    IO.println(&quot;Length OK (8+ chars): &quot; + longEnough);<br>    IO.println(&quot;Has number: &quot; + hasNumber);<br>    if (longEnough &amp;&amp; hasNumber) {<br>        IO.println(&quot;Password is strong!&quot;);<br>    } else {<br>        IO.println(&quot;Password is weak.&quot;);<br>    }<br>}<br><br>boolean isLongEnough(String password) {<br>    return password.length() &gt;= 8;<br>}<br><br>boolean containsNumber(String password) {<br>    for (int i = 0; i &lt; password.length(); i++) {<br>        char c = password.charAt(i);<br>        if (c &gt;= &#39;0&#39; &amp;&amp; c &lt;= &#39;9&#39;) {<br>            return true;<br>        }<br>    }<br>    return false;<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>We break the password validation into smaller methods</li><li>Each method checks one thing</li><li>Small methods are easier to understand and modify</li><li>password.length() returns the length of a string (note the parentheses — it’s a method!)</li><li>password.charAt(i) gets the character at index i</li><li><strong>char</strong> is a type for a single character</li></ul><p><strong>New concepts introduced:</strong></p><ul><li>.length() for strings (with parentheses, unlike arrays!)</li><li>.charAt(index) gets character at position</li><li><strong>char</strong> type for single characters</li></ul><h3>Try to find what is wrong in the following code</h3><pre>// 1<br>int multiply(int a, int b) {<br>    int result = a * b;<br>}</pre><pre>// 2<br>void printMessage(String msg) {<br>    IO.println(msg);<br>    return msg;<br>}</pre><pre>// 3<br>boolean isPositive(int number) {<br>    if (number &gt; 0) {<br>        return true;<br>    }<br>}</pre><pre>// 4<br>String getName() {<br>    return 42;<br>}</pre><p><strong>Answers:</strong></p><ol><li>Missing return statement — method returns int but doesn&#39;t return anything. Should be return result; or return a * b;</li><li>void method can’t return a value — void means “no return value”. Remove return msg; or change return type to String.</li><li>Missing return for some paths — if number is NOT positive (0 or negative), nothing is returned. Should add else { return false; } or return number &gt; 0;</li><li>Wrong return type — method returns String but trying to return an int (42). Should return a string like return &quot;42&quot;; or change return type to int.</li></ol><h3>Why Is It Important</h3><p><strong>Methods organize your code.</strong> Instead of one giant main() with 500 lines, you break it into small methods with clear purposes. This makes code easier to read, understand, and fix.</p><p><strong>Return types make methods predictable.</strong> When you see boolean isValid(), you know it returns true or false. When you see int calculateAge(), you know it returns a number. Clear expectations make coding easier.</p><p><strong>void for actions, other types for calculations.</strong> Use void when the method does something (prints, saves file). Use return types when the method computes something (calculates, checks, generates).</p><p><strong>Boolean methods improve readability.</strong> Compare if (age &gt;= 18) with if (isAdult(age)). The second is clearer - it reads like English. Boolean methods make your conditions self-documenting.</p><p><strong>Methods enable reuse.</strong> Write calculateAverage() once, use it everywhere. Change it in one place, the change applies everywhere. This is the power of methods.</p><p><strong>Small methods are easier to test.</strong> You can test isEven() independently. If it works alone, it works everywhere. Breaking code into methods makes finding bugs much easier.</p><h3>Key Takeaways</h3><ul><li>Methods can return void, int, String, boolean, or any type</li><li>void means no return value (just does something)</li><li>Non-void methods MUST have return statement</li><li>return sends value back to caller</li><li>Boolean methods perfect for checks: isValid(), hasValue()</li><li>Methods can call other methods</li><li>Small, focused methods = cleaner code</li><li>String .length() has parentheses, array .length doesn&#39;t</li></ul><h3>Next</h3><ul><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-10-random-numbers-math-f37be0dae36e">Java 101 — Lesson 10: Random Numbers &amp; Math</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09c729cb24ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 101 — Lesson 8: Arrays — Storing Multiple Values]]></title>
            <link>https://ondrej-kvasnovsky.medium.com/java-101-lesson-8-arrays-storing-multiple-values-200df7c6c8c7?source=rss-9242585892a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/200df7c6c8c7</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ondrej Kvasnovsky]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 03:59:24 GMT</pubDate>
            <atom:updated>2025-11-02T20:53:05.843Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 101 — Lesson 8: Arrays — Storing Multiple Values</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETwLDPQxEAYyBzo_kkIVMw.jpeg" /></figure><h3>Grammar (Syntax)</h3><p>So far, we’ve stored single values in variables — one number, one piece of text. But what if you need to store 100 test scores, or 50 player names? That’s where <strong>arrays</strong> come in.</p><p>An <strong>array</strong> is a container that holds multiple values of the same type. Think of it like a row of numbered boxes, where each box holds one value.</p><p>The pattern for creating an array is:</p><pre>type[] arrayName = new type[size];</pre><p>Let’s break it down:</p><ul><li><strong>type[]</strong> — the type with square brackets means “array of this type”</li><li>arrayName — the name of your array (use camelCase)</li><li><strong>new </strong>type[size] — creates an array with that many slots</li><li>size — how many values the array can hold</li></ul><p>The pattern for accessing an array element is:</p><pre>arrayName[index]</pre><p>Let’s break it down:</p><ul><li>index — the position (starts at 0, not 1!)</li><li>First element is at index 0, second at index 1, etc.</li></ul><p>The pattern for creating an array with initial values is:</p><pre>type[] arrayName = {value1, value2, value3};</pre><p><strong>Important:</strong> Array indexes start at 0. An array of size 5 has indexes 0, 1, 2, 3, 4.</p><h3>Examples</h3><h4><strong>Step 1: Create your file</strong></h4><p>Create a file called ArrayExamples.java</p><h4><strong>Step 2: Creating and using your first array</strong></h4><pre>void main() {<br>    // Create an array that holds 5 integers<br>    int[] scores = new int[5];<br><br>    // Put values into the array<br>    scores[0] = 85;<br>    scores[1] = 92;<br>    scores[2] = 78;<br>    scores[3] = 95;<br>    scores[4] = 88;<br><br>    // Read values from the array<br>    IO.println(&quot;First score: &quot; + scores[0]);<br>    IO.println(&quot;Third score: &quot; + scores[2]);<br>    IO.println(&quot;Last score: &quot; + scores[4]);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>int[] scores - declares an array that will hold integers</li><li>new int[5] - creates an array with 5 slots (indexes 0-4)</li><li><strong>Square brackets </strong><strong>[ ]</strong> are used to access specific positions</li><li>scores[0] is the first element, scores[1] is the second, etc.</li></ul><p>Output:</p><pre>First score: 85<br>Third score: 78<br>Last score: 88</pre><h4><strong>Step 3: Creating an array with initial values</strong></h4><pre>void main() {<br>    // Shorter way - create and fill at the same time<br>    int[] ages = {15, 16, 14, 15, 17};<br><br>    IO.println(&quot;Student 1 age: &quot; + ages[0]);<br>    IO.println(&quot;Student 2 age: &quot; + ages[1]);<br>    IO.println(&quot;Student 5 age: &quot; + ages[4]);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>The {15, 16, 14, 15, 17} syntax creates an array and fills it in one line</li><li>Java automatically figures out the size (5 elements in this case)</li><li>This is faster when you know all the values upfront</li></ul><p>Output:</p><pre>Student 1 age: 15<br>Student 2 age: 16<br>Student 5 age: 17</pre><h4><strong>Step 4: Array length and loops</strong></h4><pre>void main() {<br>    String[] names = {&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;Diana&quot;};<br><br>    // .length tells you how many elements<br>    IO.println(&quot;Number of students: &quot; + names.length);<br>    // Loop through all elements<br>    for (int i = 0; i &lt; names.length; i++) {<br>        IO.println((i + 1) + &quot;. &quot; + names[i]);<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>arrayName.length gives you the number of elements in the array</li><li>The dot . accesses the length property (not a method, no parentheses!)</li><li>We use a for loop with i &lt; names.length to visit each element</li><li>(i + 1) prints 1, 2, 3, 4 instead of 0, 1, 2, 3</li></ul><p>Output:</p><pre>Number of students: 4<br>1. Alice<br>2. Bob<br>3. Charlie<br>4. Diana</pre><h4><strong>Step 5: Finding the maximum value</strong></h4><pre>void main() {<br>    int[] numbers = {45, 89, 23, 67, 91, 34};<br><br>    int max = numbers[0]; // Start with first element<br>    for (int i = 1; i &lt; numbers.length; i++) {<br>        if (numbers[i] &gt; max) {<br>            max = numbers[i];<br>        }<br>    }<br>    IO.println(&quot;Highest number: &quot; + max);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>We start by assuming the first element is the maximum</li><li>Loop through the rest (starting at index 1)</li><li>If we find a bigger number, update max</li><li>This is a common pattern for finding min/max values</li></ul><p>Output:</p><pre>Highest number: 91</pre><h4><strong>Step 6: Calculating average</strong></h4><pre>void main() {<br>    int[] testScores = {85, 92, 78, 95, 88};<br><br>    int sum = 0;<br>    for (int i = 0; i &lt; testScores.length; i++) {<br>        sum = sum + testScores[i];<br>    }<br>    int average = sum / testScores.length;<br>    IO.println(&quot;Total scores: &quot; + sum);<br>    IO.println(&quot;Average score: &quot; + average);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>Initialize sum to 0</li><li>Loop through array, adding each score to sum</li><li>Divide total by number of scores to get average</li><li>Arrays are perfect for this kind of calculation</li></ul><p>Output:</p><pre>Total scores: 438<br>Average score: 87</pre><h4><strong>Step 7: Searching for a value</strong></h4><pre>void main() {<br>    String[] fruits = {&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;, &quot;grape&quot;, &quot;mango&quot;};<br><br>    IO.println(&quot;Enter a fruit to search:&quot;);<br>    String searchFruit = IO.readln();<br>    boolean found = false;<br><br>    for (int i = 0; i &lt; fruits.length; i++) {<br>        String fruit = fruits[i];<br>        if (fuit.equals(searchFruit)) {<br>            found = true;<br>            break;<br>        }<br>    }<br>    if (found) {<br>        IO.println(&quot;Fruit &quot; + searchFruit + &quot; found!!&quot;);<br>    } else {<br>        IO.println(&quot;Not found&quot;);<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>Use a boolean variable to track if we found the item</li><li><strong>break</strong> keyword exits the loop early (no need to keep searching)</li><li>Check found after the loop to show the result</li></ul><p><strong>New concept:</strong> The <strong>break</strong> keyword immediately exits a loop.</p><h4><strong>Step 8: Working with multiple arrays</strong></h4><pre>void main() {<br>    String[] students = {&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;};<br>    int[] scores = {92, 85, 78};<br> <br>    IO.println(&quot;Student Scores:&quot;);<br>    for (int i = 0; i &lt; students.length; i++) {<br>        IO.println(students[i] + &quot;: &quot; + scores[i]);<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>Two arrays with related data (parallel arrays)</li><li>Same index in both arrays refers to the same person</li><li>students[0] and scores[0] both relate to Alice</li><li>Common pattern for organizing related data</li></ul><p>Output:</p><pre>Student Scores:<br>Alice: 92<br>Bob: 85<br>Charlie: 78</pre><h3>Try to find what is wrong in the following code</h3><pre>// 1<br>void main() {<br>    int[] numbers = new int[5];<br>    numbers[5] = 100;<br>}</pre><pre>// 2<br>void main() {<br>    String[] names = {&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;};<br>    IO.println(names.length());<br>}</pre><pre>// 3<br>void main() {<br>    int[] scores = {85, 90, 78};<br>    for (int i = 0; i &lt;= scores.length; i++) {<br>        IO.println(scores[i]);<br>    }<br>}</pre><pre>// 4<br>void main() {<br>    int numbers[] = new int[3];<br>    numbers = {10, 20, 30};<br>}</pre><p><strong>Answers:</strong></p><ol><li>Index out of bounds — array of size 5 has indexes 0–4, not 5. Should be numbers[4] = 100; for the last element.</li><li>.length is a property, not a method - no parentheses needed. Should be names.length not names.length().</li><li>Loop condition goes too far — should be i &lt; scores.length not i &lt;= scores.length. The &lt;= tries to access index 3 which doesn&#39;t exist (0, 1, 2 are valid).</li><li>Can’t reassign array with {} syntax after creation - the {} syntax only works during declaration. Should declare and initialize together: int[] numbers = {10, 20, 30};</li></ol><h3>Why Is It Important</h3><p><strong>Arrays store related data together.</strong> Instead of creating score1, score2, score3... you create one array. This makes your code cleaner and easier to manage.</p><p><strong>Arrays work perfectly with loops.</strong> You can process 100 items with the same 3 lines of loop code. Without arrays, you’d need 100 separate variables and 100 lines of code.</p><p><strong>Real programs use arrays everywhere.</strong> Lists of users, game scores, shopping cart items, search results — arrays are fundamental to storing and processing collections of data.</p><p><strong>Array indexes start at 0.</strong> This is crucial to remember! It might seem weird at first, but it’s standard in most programming languages. The first element is always at index 0.</p><p>.length<strong> prevents errors.</strong> Using array.length in loops instead of hardcoding numbers means your code works even if the array size changes. It&#39;s safer and more flexible.</p><p><strong>Arrays have a fixed size.</strong> Once you create an array with new int[5], it always has 5 slots. You can change the values inside, but not the size. (Later you&#39;ll learn about ArrayList for dynamic sizing.)</p><h3>Key Takeaways</h3><ul><li>Arrays store multiple values of the same type</li><li>Create array: int[] numbers = new int[5];</li><li>Initialize with values: int[] numbers = {10, 20, 30};</li><li>Access elements: numbers[0], numbers[1], etc.</li><li>Indexes start at 0, not 1</li><li>Use .length to get size (no parentheses!)</li><li>Loop through arrays: for (int i = 0; i &lt; array.length; i++)</li><li>break exits a loop early</li></ul><h3>Next</h3><ul><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-9-methods-return-types-and-organization-09c729cb24ef">Java 101 — Lesson 9: Methods — Return Types and Organization</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=200df7c6c8c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 101 — Lesson 7: User Input — Making Interactive Programs]]></title>
            <link>https://ondrej-kvasnovsky.medium.com/java-101-lesson-7-user-input-making-interactive-programs-a4f7a313b2c9?source=rss-9242585892a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4f7a313b2c9</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ondrej Kvasnovsky]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 03:47:36 GMT</pubDate>
            <atom:updated>2025-11-02T20:51:51.592Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 101 — Lesson 7: User Input — Making Interactive Programs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMFzy0oyYuJTXXapTf4Z8g.jpeg" /></figure><h3>Grammar (Syntax)</h3><p>So far, all our programs have used fixed values — numbers and text we wrote in the code. <strong>User input</strong> lets your program ask questions and respond to what the user types. This makes programs interactive!</p><p>The pattern for reading a number from the user is:</p><pre>String variableName = IO.readln();</pre><p>Let’s break it down:</p><ul><li><strong>IO.readln()</strong>— waits for the user to type text and press Enter</li><li>The text (a whole line) gets stored in the String variable</li><li>This is a method that <strong>returns</strong> a String value</li></ul><p>The pattern for reading a number from the user is:</p><pre>import java.util.Scanner;<br><br>Scanner scanner = new Scanner(System.in);<br>int variableName = scanner.nextInt();</pre><p>Let’s break it down:</p><ul><li>import java.util.Scanner; — brings in the Scanner class (put at the very top of your file)</li><li>Scanner scanner = new Scanner(System.in);<strong> </strong>— creates a Scanner object to read from keyboard</li><li>scanner.nextInt() — waits for the user to type a number and press Enter</li><li>The number the user types gets stored in the variable</li></ul><p><strong>Important:</strong> When your program runs IO.readln() or scanner.nextInt(), it <strong>pauses and waits</strong> for the user to type something and press Enter.</p><blockquote><strong><em>Learning Tip:</em></strong><em> You’ll learn much faster if you type out the code yourself instead of copying it. Your fingers will start remembering the patterns, and you’ll catch mistakes that teach you how Java really works. Reading is good, but typing is how you truly learn to code!</em></blockquote><h3>Examples</h3><h4><strong>Step 1: Create your file</strong></h4><p>Create a file called UserInput.java</p><h4><strong>Step 2: Reading text from the user</strong></h4><pre>void main() {<br>    IO.println(&quot;What is your name?&quot;);<br>    String name = IO.readln();<br><br>    IO.println(&quot;Hello, &quot; + name + &quot;!&quot;);<br>    IO.println(&quot;Nice to meet you.&quot;);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>IO.readln() reads whatever text the user types</li><li>The entire line becomes a String</li><li>We can use that String like any other variable</li></ul><p>When you run this with java UserInput.java:</p><pre>What is your name?<br>Alex                  ← user types this<br>Hello, Alex!<br>Nice to meet you.</pre><h4><strong>Step 3: Reading a number from the user</strong></h4><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    IO.println(&quot;What is your age?&quot;);<br>    int age = scanner.nextInt();<br><br>    IO.println(&quot;You are &quot; + age + &quot; years old!&quot;);<br>}</pre><p><strong>What’s happening:</strong></p><ol><li>Import Scanner at the top of the file</li><li>Create a Scanner object to read from the keyboard</li><li>Print a question to the user</li><li>scanner.nextInt() pauses and waits for the user to type a number</li><li>User types a number (like 15) and presses Enter</li><li>The number is stored in the age variable</li></ol><h4><strong>Step 4: Combining multiple inputs</strong></h4><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    IO.println(&quot;Enter your first name:&quot;);<br>    String firstName = IO.readln();<br><br>    IO.println(&quot;Enter your last name:&quot;);<br>    String lastName = IO.readln();<br><br>    IO.println(&quot;Enter your age:&quot;);<br>    int age = scanner.nextInt();<br><br>    String fullName = firstName + &quot; &quot; + lastName;<br>    IO.println(&quot;\nProfile Created:&quot;);<br>    IO.println(&quot;Name: &quot; + fullName);<br>    IO.println(&quot;Age: &quot; + age);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>We can call IO.readln() and scanner.nextInt() multiple times</li><li>Each call waits for user input</li><li>\n in a string creates a new line (line break)</li><li>We combine the inputs to create a user profile</li></ul><h4><strong>Step 5: Using input with conditionals</strong></h4><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    IO.println(&quot;Enter the temperature in Celsius:&quot;);<br>    int celsius = scanner.nextInt();<br><br>    if (celsius &lt; 0) {<br>        IO.println(&quot;It&#39;s freezing!&quot;);<br>    } else if (celsius &lt; 15) {<br>        IO.println(&quot;It&#39;s cold - wear a jacket.&quot;);<br>    } else if (celsius &lt; 25) {<br>        IO.println(&quot;Nice weather!&quot;);<br>    } else {<br>        IO.println(&quot;It&#39;s hot!&quot;);<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>We read a number from the user with Scanner</li><li>Use conditionals to make decisions based on that input</li><li>Different messages appear depending on what the user types</li></ul><h4><strong>Step 6: Using input with loops</strong></h4><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    IO.println(&quot;How many times should I greet you?&quot;);<br>    int count = scanner.nextInt();<br><br>    IO.println(&quot;What is your name?&quot;);<br>    String name = IO.readln();<br><br>    for (int i = 1; i &lt;= count; i++) {<br>        IO.println(i + &quot;. Hello, &quot; + name + &quot;!&quot;);<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>User input determines how many times the loop runs</li><li>We read both a number (Scanner) and text (IO.readln)</li><li>The loop uses the count variable in its condition</li></ul><p>When you run this:</p><pre>How many times should I greet you?<br>3<br>What is your name?<br>Jordan<br>1. Hello, Jordan!<br>2. Hello, Jordan!<br>3. Hello, Jordan!</pre><h4><strong>Step 7: Simple calculator with user input</strong></h4><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    IO.println(&quot;Simple Calculator&quot;);<br>    IO.println(&quot;Enter first number:&quot;);<br>    int num1 = scanner.nextInt();<br><br>    IO.println(&quot;Enter second number:&quot;);<br>    int num2 = scanner.nextInt();<br><br>    IO.println(&quot;\nResults:&quot;);<br>    IO.println(num1 + &quot; + &quot; + num2 + &quot; = &quot; + (num1 + num2));<br>    IO.println(num1 + &quot; - &quot; + num2 + &quot; = &quot; + (num1 - num2));<br>    IO.println(num1 + &quot; × &quot; + num2 + &quot; = &quot; + (num1 * num2));<br><br>    if (num2 != 0) {<br>        IO.println(num1 + &quot; ÷ &quot; + num2 + &quot; = &quot; + (num1 / num2));<br>    } else {<br>        IO.println(&quot;Cannot divide by zero!&quot;);<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>We read two numbers from the user using Scanner</li><li>Perform all four basic operations</li><li><strong>Parentheses</strong> around (num1 + num2) ensure we do addition before combining with the string</li><li>Check if num2 is not zero before dividing (avoid error)</li></ul><p>When you run this:</p><pre>Simple Calculator<br>Enter first number:<br>20<br>Enter second number:<br>5<br><br>Results:<br>20 + 5 = 25<br>20 - 5 = 15<br>20 × 5 = 100<br>20 ÷ 5 = 4</pre><h4><strong>Step 8: Input validation — checking if input is reasonable</strong></h4><pre>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br><br>    IO.println(&quot;Enter your age:&quot;);<br>    int age = scanner.nextInt();<br><br>    if (age &lt; 0 || age &gt; 120) {<br>        IO.println(&quot;That doesn&#39;t seem like a valid age!&quot;);<br>    } else {<br>        IO.println(&quot;You are &quot; + age + &quot; years old.&quot;);<br><br>        if (age &gt;= 18) {<br>            IO.println(&quot;You are an adult.&quot;);<br>        } else {<br>            IO.println(&quot;You are a minor.&quot;);<br>        }<br>    }<br>}</pre><p><strong>What’s happening:</strong></p><ul><li><strong>Input validation</strong> means checking if the user entered reasonable data</li><li>We check if age is negative or impossibly high</li><li>If invalid, show an error message</li><li>If valid, continue with the program logic</li><li>This prevents your program from working with nonsense data</li></ul><h3>Try to find what is wrong in the following code</h3><pre>// 1<br>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br>    IO.println(&quot;Enter a number:&quot;);<br>    String number = scanner.nextInt();<br>    IO.println(&quot;You entered: &quot; + number);<br>}</pre><pre>// 2<br>void main() {<br>    IO.println(&quot;What is your name?&quot;);<br>    int name = IO.readln();<br>    IO.println(&quot;Hello &quot; + name);<br>}</pre><pre>// 3<br>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br>    int age = scanner.nextInt();<br>    IO.println(&quot;You are &quot; + age);<br>}</pre><pre>// 4<br>import java.util.Scanner;<br><br>void main() {<br>    Scanner scanner = new Scanner(System.in);<br>    IO.println(&quot;Enter first number:&quot;);<br>    int num1 = scanner.nextInt();<br>    IO.println(&quot;Enter second number:&quot;);<br>    int num2 = scanner.nextInt();<br>    IO.println(&quot;Sum: &quot; + num1 + num2);<br>}</pre><p><strong>Answers:</strong></p><ol><li>Wrong type — scanner.nextInt() returns an int, not a String. Should be int number = scanner.nextInt();</li><li>Wrong type — IO.readln() returns a String, not an int. Should be String name = IO.readln();</li><li>Missing prompt — the user doesn’t know what to type! Always print a message before reading input.</li><li>Missing parentheses — will print “510” instead of “15” for inputs 5 and 10. Should be &quot;Sum: &quot; + (num1 + num2) to force addition first.</li></ol><h3>Why Is It Important</h3><p><strong>Interactive programs are useful programs.</strong> Without input, every program does the same thing every time. Input lets users control what happens — enter their name, choose options, play games, enter data.</p><p><strong>Reading input is a fundamental skill.</strong> Every useful program you’ve ever used takes input — typing messages, clicking buttons, entering numbers. IO.readln() and Scanner are your first tools for making programs that respond to users.</p><p><strong>Type matters when reading input.</strong> Scanner’s nextInt() reads numbers, IO.readln() reads text. Using the wrong one causes errors. Understanding this prepares you for more complex input handling later.</p><p><strong>Always prompt before reading.</strong> Users need to know what to type. A program that just waits for input with no message is confusing. Always print a question or instruction first.</p><p><strong>Input validation prevents errors.</strong> Users make mistakes — they type negative ages, divide by zero, enter text instead of numbers. Good programs check if input makes sense before using it.</p><h3>Key Takeaways</h3><ul><li>IO.readln() reads text from the user</li><li>scanner.nextInt() reads a number from the user (requires Scanner import)</li><li>Both methods pause and wait for user input</li><li>Always print a prompt before reading input</li><li>Match variable type: int for scanner.nextInt(), String for IO.readln()</li><li>Use parentheses (num1 + num2) for math in print statements</li><li>Input validation checks if data is reasonable</li><li>\n creates a new line in strings</li></ul><h3>Next</h3><ul><li><a href="https://ondrej-kvasnovsky.medium.com/java-101-lesson-8-arrays-storing-multiple-values-200df7c6c8c7">Java 101 — Lesson 8: Arrays — Storing Multiple Values</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4f7a313b2c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>