mdinfotech.net  



Section 1

Copy and paste this template into your notes:
Boolean Expressions and if statements
  1. Make a table of the 6 relational operators, what each one does, and what their order of precedence is.
  2. Make a table of the 3 logical operators, what each one does, and what their order of precedence is.
  3. What is the anatomy of an if/else statement?
  4. Draw a flow chart that represents the if/else
  5. What does an else-if statement look like?
  6. When should an else-if statement be used?

Lesson in class. Watch Boolean Expressions and the if-statement from 00:00 to 26:24 (you can skip the last half of the video) and answer the above questions in your notes.

You can also use the links below to help answer the questions:
  1. Read if..else at W3 Schools.
  2. Read Boolean Expressions Tutorial
  3. Read Boolean Operators
  4. Read Operator Precedence
Exercise:

Do the Boolean Expressions Exercises on Classroom

Additional Resources:
  1. Iffy Programming Tutorial
  2. Or else... Tutorial
  3. True or False?
  4. Expressions, Statements and Blocks Tutorial.
  5. Control Flow Statements Tutorial.
a) Output Method - displayWelcomeMessage()
  1. Copy and paste MathQuizPart1.java.
  2. Follow the instructions to write the method displayWelcomeMessage() and the test driver main().
b) Calculate something - generateRandomNumber()
  1. Watch in class: Math.random()
  2. Copy and paste MathQuizPart2.java.
  3. Follow the instructions to write the method generateRandomNumber() and the test driver main().
c) User Input - askQuestion()
  1. Copy and paste MathQuizPart3.java.
  2. Follow the instructions to write the method askQuestion() and the test driver main().
d) Make a Decision - giveFeedback()
  1. Copy and paste MathQuizPart4.java.
  2. Follow the instructions to write the method giveFeedback() and the test driver main().
e) Complete the Program
  1. Begin with your solution to MathQuizPart4.java.
  2. In main, use generateRandomNumber to generate a third value between 0 and 4.
  3. Use the random value between 0 and 4 to select an operation (+, -, *, /, %) to determine which of the five calculation to do (instead of just sum)
  4. Modify askQuestion() so that it has one additional parameter: char op. ModifyaskQuestion() so it asks the user to do the math operation op.
  5. Calculate the actual result of the random operator on num1 and num2, and pass it to giveFeedback() to provide feedback.
  1. Watch and code along with Methods in Java
  2. Watch and code along with Return Statements in Java
  3. Read this article about Boolean Methods
  4. Write the method below AND a test driver:
    TestDriver: In programming, a "test driver method" refers to a piece of code specifically designed to execute and verify the functionality of another piece of code, usually a function or module, by providing input data and checking the output.

    main() will be our test driver for all the methods we write in this unit.
    Method: isLeap()
    1. Write a method called isLeap() that has one formal parameter: the year, and returns true if it is a leap year, otherwise it returns false.
    2. Only use if...else statements, do not use the ternary operator.
    3. Write a test driver to your method for a number of valid leap years, valid non-leap years, boundary values like 0, and extreme cases like -1, and Integer.MAX_VALUE.
    4. The rules to determine if a year is a Leap Year are:
      1. A year divisible by 4 is a leap year (2004, 2008...), unless
      2. it is also divisible by 100 (2100, 2200...) in which case it is not a leap year.
      3. There is an exception. A year divisible by 400 is a leap year (2000, 2400...).
    5. Carefully consider the order in which the above checks should be done to write a simple, accurate, algorithm

    A test driver is a main method that tests your method isLeap() with a variety of inputs to ensure it works. A sample test driver might look like this:

    			System.out.println("2000 is a leap year: " + isLeap(2000));
    			System.out.println("2001 is a leap year: " + isLeap(2001));
    			System.out.println("2002 is a leap year: " + isLeap(2002));
    			System.out.println("2003 is a leap year: " + isLeap(2003));
    			System.out.println("2004 is a leap year: " + isLeap(2004));
    			System.out.println("1800 a leap year: " + isLeap(1800));
    			System.out.println("-1 is a leap year: " + isLeap(-1));
    			System.out.println(Integer.MAX_VALUE + " is a leap year: " + isLeap(Integer.MAX_VALUE));
    	
    			
    			

    Write a test driver that proves your method isLeap() works.

Read this website about the ?: operator, a shorter version of the if statement.

switch statement for integers, and enumerated types like Strings, fall through, and using fall through to achieve > or <

Ms Wear's Slides.

  1. Read about the ?: operator.
  2. Read this Switch Statement Tutorial
  3. Write a method called getMaxDays(int m, int y) that has two parameters: m which is the numerical value of the month (Jan = 1, ..., Dec = 12) and y which is the year.
  4. Use a switch statement to return the number of days (that is, the return type is int) in the month (Jan has 31, Feb has 28 OR 29, ..., Dec 31)
  5. For February, use the ternary operator AND a call to isLeap to decide whether to return 28 or 29. **Note: You will need to copy and paste isLeap into the current program.
  6. If the month is not between 1 and 12, return -1. Note: -1 is an invalid number of days and indicates to the calling method that the input was invalid. It is the job of the calling method, not getMaxDays to ensure the input is valid.
  7. Write a test driver to test your method for all 12 months and boundary values such as -1, 0, and 13, and extreme values like Integer.MAX_VALUE.
Ask Ms. Wear to give the 100/80/60 Quiz - Switch Statements
Ask Ms. Wear to give the CS 11 Control Flow Statements Quiz.

Using Flowcharts to Plan Programming Assignments

What is a Flowchart? A flowchart is a visual tool used to represent the flow of a process or a program. In programming, flowcharts help break down the logic of a task into steps, using different symbols to represent different types of actions or decisions.


Why Use Flowcharts? Flowcharts are especially useful in the early stages of planning a programming assignment because they:

  • Clarify the program’s structure.
  • Help visualize complex logic before writing any code.
  • Allow you to catch potential issues early, like infinite loops or logic errors.
  • Provide a roadmap for translating the steps into code.

Basic Flowchart Symbols

  1. Oval (Start/End): Marks the beginning or end of the program.

    • Example: Start or End
  2. Rectangle (Process/Action): Represents a process, like a computation or an action taken by the program.

    • Example: Get user input, Calculate total
  3. Diamond (Decision): Used for decision-making or branching logic. It represents a point where the program must make a choice based on a condition.

    • Example: Is the value valid? → Yes/No
  4. Arrows: Show the flow of control, guiding the sequence in which steps are executed.


Steps to Create a Flowchart for a Programming Assignment

  1. Understand the problem: Read through the assignment and identify the key tasks your program needs to accomplish.

  2. Break the problem into steps: Divide the problem into smaller logical steps. Think about what data you need, what decisions need to be made, and how the program will flow.

  3. Draw the flowchart:

    • Start with an oval symbol.
    • Use rectangles for processes like input, calculations, and actions.
    • Use diamonds for decision points (e.g., "Is the input valid?").
    • Connect the steps with arrows to show the program flow.
    • End with an oval symbol to represent the program's completion.
  4. Review and refine: Check the flowchart to ensure that all possible paths are covered, including edge cases. Make sure it clearly matches the logic of the assignment.


Example Flowchart for User Input Validation

Here’s a simple flowchart for a program that checks if a user’s input is valid:

simple flow chart

This flowchart outlines a basic program where user input is validated. If the input is invalid, the program displays an error message and asks for input again.


Tips for Using Flowcharts in Programming Assignments

  • Simplify: Start simple. Focus on the main logic first, then refine your flowchart to include error handling and edge cases.
  • Collaborate: Flowcharts are a great way to communicate your ideas to peers or teachers for feedback.
  • Translate to Code: Once your flowchart is complete, use it as a guide to write your code, step by step.

By planning your programming assignments with flowcharts, you'll have a clearer understanding of your program's structure, making it easier to write efficient, well-organized code.

Complete this activity as a pairs programming exercise.

Exercise:

  1. Draw a flow chart for a program that asks the user to enter a positive whole number, and if it is not a valid number, or is negative, displays an error and requires the user to reenter the value. Once a valid positive whole number has been entered, display the number as valid. Draw the flow chart on paper.
  2. Get the flow chart approved by Ms. Wear.
  3. Write and test the program in Eclipse.
  4. Show the completed program to Ms. Wear
User Friendly software will not crash, throw exceptions, or stop working if the user enters invalid data. Instead, it should present a descriptive error message and provide the user another opportunity to enter the data. To do this you will need:

Lesson on how to write code that will not crash, is user friendly, and uses dialog boxes.

New topics include Option Panes, and Try...Catch, used with do..while and break/continue. Program along with Ms. Wear in class.

If the user clicks "Cancel" on a dialog box, you want the program to shutdown cleanly. You will need the code below:


        String input = "";  // user input always comes in as string data
        int num = 0;        // parsed user input
        String error = ""; // error message

        // repeat while data invalid
        do {

            // get user input
            input = JOptionPane.showInputDialog(error + "Enter stuff!");
    
            // if the user clicks cancel, input will be null, then exit the program
            if (input == null) {
                System.out.println("You clicked cancel");
                System.exit(0);
            }
            
            // if needed, parse String to numerical data
            try {
               num = Integer.parseInt(input);
            } catch (Exception e) {
               error = "Invalid numerical value entered.";
               continue;
            } // catch
            
            // check additional validity with if statements
            if (num < 0) {
                 error = "The number must be positive. Please try again. ";
                 continue;
            } 
            
            break;  // exit loop if all data entered valid
        } while(true);
 
        JOptionPane.showMessageDialog(null, "The valid number is " + num);

        
In this exercise, you will write methods with the purpose to get input from the user, or to display output to the user. These are called Input/Output methods.
  1. Write an input method called getNumberFromUser()
    • it uses a dialog box to ask the user for the year and returns the value of the year.
    • This method has no parameters
    • If the user does not enter a positive integer, the method should repeat the question with an appropriate error message in the same dialog box until valid input is gathered.
    • It should return an int.
  2. Write an output method called showResult() that has a string as a parameter and shows the string in a JOptionPane.showMessageDialog.
  3. Use this test driver to test your methods:
                          int num = getNumberFromUser();
                          showResult("You entered the number " + num);
                     

When you hand in a printed (hard copy) version of your code, it will be marked in two categories, each out of 10:

1. Commenting and Formatting (10 marks)
2. Efficiency and Design (10 marks)

These are based on the same principles real software engineers use to write professional, readable, and efficient code.


1. Commenting and Formatting (10 marks)

This section is about how your code looks and how easy it is to understand.

Think of your code as a story. The comments are the narration that helps others (and your future self) follow along.

Must-Haves in Every Program:

  • Program header at the top with:

    • Program name
    • Author
    • Date
    • Purpose
  • In-code comments that explain what your code is doing — especially before tricky sections.
  • Blank line before in-code comments (so they stand out clearly).
  • Don’t put code inside comments (// do..while loop ← never do this).
  • Label closing brackets (example: } // end main).
  • Indent 4 spaces after every {.
  • Use spaces around operators (x + y, not x+y).
  • Meaningful names for variables and methods (totalScore, not x1).
  • Declare variables at the top of each method, one variable per line, and initialize.
  • Add a brief comment above each method describing what it does.
  • Check spelling in variable names, user messages, and comments.
  • Follow standard Java coding conventions: Original Java Coding Conventions

Goal: Anyone who knows Java (including you, a month from now) should be able to read your code and instantly understand what’s happening.


2. Efficiency and Design (10 marks)

You might think, "If my program works, that’s good enough." Wrong.

A working program is the starting point, not the finish line. Once it works, you need to ask:

“How well is it written?”

Let’s break this down into the four key principles every good programmer follows:


1. Readability

Code should be easy to read and understand. You (or another programmer) might need to modify it later, and confusing code wastes time.

To make your code readable:

  • Keep all variable declarations at the top of methods.
  • Write comments that explain why something is done, not just what it does.
  • Use simple, clear logic instead of clever tricks.

    Example: Avoid nested ternary operators — they’re hard to read!


2. Reusability

Don’t repeat yourself! If you find yourself writing the same code twice, that’s a sign you should make a method instead.

Why? Because when you need to fix or improve it later, you’ll only need to change one place.


3. Efficiency

Efficient programs run faster and use less memory. This matters most for big programs, but it’s good practice to start thinking about it now.

Examples:

  • If you have nested loops, can the inner one run fewer times?
  • Are you doing unnecessary calculations inside a loop?

Small improvements in logic can make your code much more efficient.


4. Elegance

Elegance means your code not only works — it feels right. It’s clear, simple, and logically structured.

It’s hard to measure elegance, but you can recognize it when you see it:

  • Everything is neatly organized.
  • The logic flows naturally.
  • You’re proud to show it off.

For inspiration, read "Programming is an Art." It shows how coding well is about craftsmanship, not just correctness.


Summary: How to Earn Full Marks

Category Description What to Do
Commenting & Formatting (10) Your code is readable, clean, and well-commented. Use headers, method comments, spacing, indentation, and meaningful names.
Efficiency & Design (10) Your program works well, avoids repetition, and uses smart logic. Focus on readability first, then reusability, efficiency, and elegance.

Final Thought

Your goal isn’t just to make your program run — it’s to make it understandable, reusable, efficient, and elegant. That’s what separates a coder from a software engineer.

Overview

Someone named Fred has written a messy Java program. It works—sort of—but it breaks nearly every rule of good coding. Your mission is to refactor, improve, and redesign the program so that it meets professional software engineering standards.


Learning Goals

By completing this challenge, you will:

  • Apply Java coding conventions consistently
  • Write readable, well-documented, and efficient programs
  • Refactor poor-quality code into professional-quality code
  • Evaluate another programmer’s work constructively

Part 1 – Analyze and Reformat

  1. Copy and paste the following code into your text editor (Eclipse or another IDE).
  2. Reformat and rewrite it to meet all the criteria from the lesson on:

    • Commenting and Formatting
    • Efficiency and Design
    • Java Coding Conventions

Your version should:

  • Be fully readable and properly indented
  • Contain accurate program comments and method comments
  • Use meaningful variable and class names
  • Include appropriate spacing, indentation, and labels for closing brackets
  • Correct all syntax and spelling errors
  • Follow Java naming conventions (ClassName, camelCase for variables and methods)

The “Broken” Code

/*******************************
Author: Fred
Date: Sept 15, 2025
********************************/
import javax.swing.*;
import java.awt.Graphics;

public class poorlyformatted {

public static void main(String [] args) {
   String fred, stuff;
int suzy=0;
  double george= 0;

// get string input
fred = JOptionPane.showInputDialog( "What is your name?");
   System.out.println("Hello, " + fred);   


JOptionPane.showMessageDialog(null, "Hello, " + fred); 

// get integer input
stuff =JOptionPane.showInputDialog( "Please enter an interger:");

// parse string to an integer
try {suzy=Integer.parseInt(stuff);} 
catch (Exception e) {    System.out.println("Invalid integer"); } // catch

System.out.println(suzy+" / "+2+" = "+suzy/2);   

// get double input
                  stuff=JOptionPane.showInputDialog( "Please enter a floating point numbar:");

// parse string to a double
try {
    george=Double.parseDouble(stuff);
        } catch (Exception e) {
                System.out.println("Invalid double.");
                    } // catch

System.out.println(george+" / "+2+" = "+george/2);   // display on console

System.exit(0);
    } 
}  // Greeting

Part 2 – Redesign and Improve

Once you’ve cleaned up the formatting, improve the program’s structure and add new features. Your improved version should demonstrate all the main software design principles:

Required Design Improvements

  1. Readability

    • Rewrite variable and class names to make sense.
    • Add a clear, professional program header and inline comments.
    • Simplify any confusing code or unnecessary repetition.
  2. Reusability

    • Create at least two new methods:

      • One method that asks the user for an integer and returns it
      • One method that asks for a double and returns it
    • Reuse those methods in main() to avoid duplicated input code.
  3. Usability

    • Add clear instructions and error messages for the user.
    • Use JOptionPane for both input and output to create a simple, friendly interface.
  4. Efficiency

    • Eliminate unnecessary code or repeated logic.
    • Handle invalid inputs gracefully using try-catch.
  5. Elegance

    • Add a final summary message that combines both results.
    • Make your code look clean, consistent, and “professional.”

Part 3 – Peer Review

  1. Trade computers with your assigned partner.
  2. Assess their program using the following 20-point rubric:
Category Criteria Marks
Commenting & Formatting Program header, indentation, comments, naming, spacing /10
Efficiency & Design Reusability, readability, efficiency, and elegance /10

Deduct 1 mark for each error you find in either category. Return their marked paper and discuss one improvement they could make.


Part 4 - Coding Challenge

Now add these advanced features:

  • Calculate and display the average of the integer and double entered.
  • Add a method that rounds the double to 2 decimal places before dividing.
  • Add a loop that allows the user to try again until they enter valid numbers.

Assessment

This is a completion assignment. Show me your final program completed.

You are required to write a program that reads a date from the user by asking for the day, month, and year separately. Your program should then display the date in a specific format, and it must also check for any invalid entries.

Input Format

Into 3 JOptionPane dialogs, the user will enter the date as three separate numbers:

  • Year: 4-digit number (e.g., 1982)
  • Month: Number between 1 and 12 (e.g., September is 9)
  • Day: Number based on the month and year (e.g., 1–31 depending on the month and leap year rules)

For example:

The date September 3, 1982 would be entered as:

  • Year: 1982
  • Month: 9
  • Day: 3

Output Format

In a JOptionPane dialog, your program will display the date in this format:

The valid date you entered is September 3, 1982.

Error Handling

If the user enters invalid data, the program should:

  • Display an error message in the same dialog box as the input prompt explaining exactly why the input was invalid.
  • Re-ask the user for the incorrect value (e.g., if the day is wrong, only ask for the day again).

The error checking must include:

  • Month: Must be between 1 and 12.
  • Year: Must be a positive 4 digit number.
  • Day: Must be a valid number for that particular month (e.g., 1-31). February 29 should only be allowed if it’s a leap year.
  • Leap Year Rule: February 29 is valid only on leap years, which occur when:
    • The year is divisible by 4.
    • Except years divisible by 100, unless they are also divisible by 400.

Method Requirements

You must implement and use the following methods (some are from previous assignments):

  • isLeap(int year): Determines if a year is a leap year.
  • getMaxDays(int month, int year): Returns the number of days in a given month and year.
  • getMonthName(int month): Converts the month number to its name (e.g., 9 to "September").
  • getYearFromUser(): Gets a valid year from the user.
  • getMonthFromUser(): Gets a valid month from the user.
  • getDayFromUser(int maxDays): Gets a valid day from the user.
  • main()Must call these methods as needed.

Test Cases

You should test your program with the following dates:

  • Valid Dates:
    • 1 1 2001
    • 30 9 1945
    • 29 2 1988 (leap year)
    • 29 2 2000 (leap year)
    • 29 2 2400 (valid leap year)
  • Invalid Dates:
    • 31 9 1945
    • 29 2 1987 (not a leap year)
    • 1 24 1934 (invalid month)
    • 29 2 2100 (not a leap year)

You should also test edge cases, like the user clicking Cancel or entering non-numeric values.

This is a in class, closed everything, written assessment based on the Super Duper Date Program.