Section 1
Boolean Expressions and if statements
- Make a table of the 6 relational operators, what each one does, and what their order of precedence is.
- Make a table of the 3 logical operators, what each one does, and what their order of precedence is.
- What is the anatomy of an if/else statement?
- Draw a flow chart that represents the if/else
- What does an else-if statement look like?
- 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:- Read if..else at W3 Schools.
- Read Boolean Expressions Tutorial
- Read Boolean Operators
- Read Operator Precedence
Do the Boolean Expressions Exercises on Classroom
Additional Resources:- Iffy Programming Tutorial
- Or else... Tutorial
- True or False?
- Expressions, Statements and Blocks Tutorial.
- Control Flow Statements Tutorial.
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.a) Output Method -main()
will be our test driver for all the methods we write in this unit.
displayWelcomeMessage()
- Copy and paste MathQuizPart1.java.
- Follow the instructions to write the method
displayWelcomeMessage()
and the test drivermain()
.
generateRandomNumber()
- Watch in class: Math.random()
- Copy and paste MathQuizPart2.java.
- Follow the instructions to write the method
generateRandomNumber()
and the test drivermain()
.
askQuestion()
- Copy and paste MathQuizPart3.java.
- Follow the instructions to write the method
askQuestion()
and the test drivermain()
.
giveFeedback()
- Copy and paste MathQuizPart4.java.
- Follow the instructions to write the method
giveFeedback()
and the test drivermain()
.
- Begin with your solution to MathQuizPart4.java.
- In main, use
generateRandomNumber
to generate a third value between 0 and 4. - 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)
- Modify
askQuestion()
so that it has one additional parameter:char op
. ModifyaskQuestion()
so it asks the user to do the math operationop
. - Calculate the actual result of the random operator on num1 and num2, and pass it to
giveFeedback()
to provide feedback.
if
statement.switch statement for integers, and enumerated types like Strings, fall through, and using fall through to achieve > or <
Ms Wear's Slides.
- Read this Switch Statement Tutorial
- Check out Java Coding Conventions to see how to format a switch statement.
- Read this article about Boolean Methods
- 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. - Only use if...else statements, do not use the ternary operator.
- 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
. - The rules to determine if a year is a Leap Year are:
- A year divisible by 4 is a leap year (2004, 2008...), unless
- it is also divisible by 100 (2100, 2200...) in which case it is not a leap year.
- There is an exception. A year divisible by 400 is a leap year (2000, 2400...).
- 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 about the ?: operator.
- Read this Switch Statement Tutorial
- 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) andy
which is the year. - Use a
switch
statement to return the number of days (that is, the return type isint
) in the month (Jan has 31, Feb has 28 OR 29, ..., Dec 31) - 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 pasteisLeap
into the current program. - 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, notgetMaxDays
to ensure the input is valid. - 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.
- Read this How to use a do..while.
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
Oval (Start/End): Marks the beginning or end of the program.
- Example:
Start
orEnd
- Example:
Rectangle (Process/Action): Represents a process, like a computation or an action taken by the program.
- Example:
Get user input
,Calculate total
- Example:
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
- Example:
Arrows: Show the flow of control, guiding the sequence in which steps are executed.
Steps to Create a Flowchart for a Programming Assignment
Understand the problem: Read through the assignment and identify the key tasks your program needs to accomplish.
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.
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.
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:

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:
- 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, or do it online at apps.diagram.net.
- Get the flow chart approved by Ms. Wear.
- Write and test the program in Eclipse.
- Show the completed program to Ms. Wear
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);Resources:
- Option Panes
- Catching Exceptions with Try Catch
- Variations on dialog boxes: JOptionPane. See this JOptionPane Tutorial for more information.
- Write an input method called
getYearFromUser()
- 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
.
- Write an output method called
showResult()
that has a string as a parameter and shows the string in aJOptionPane.showMessageDialog
. - Use this test driver to test your methods:
int year = getYearFromUser(); showResult("You entered the year " + year);
When you are asked to hand in and print a hard copy of your code, it will be marked in two categories: Commenting and Formatting (/10) and Efficience and Design (/10). These categories are based on the software engineering principles:
- Readability
- Coding Conventions
- Commenting
- Usability
- Efficiency
- Include program comments (program name, author, date, purpose).
- Include in-code comments.
- Leave a blank line before in-code comments
- Do not put code inside in-code comments.
- Label closing brackets.
- Indent 4 spaces after every {.
- Put spaces around operators and //.
- Use meaningful variable and method names.
- Create all your variables at the top of the method.
- Comment the purpose of every method.
- No spelling errors in variable names, user interface, or comments.
- Follow Java Coding Conventions
It's good enough if my program works right? Wrong. Your program working is the first, and most important, thing to consider. After all, a program that doesn't work is no good to anyone, and worth no marks. If you assume a program works, then is there more that should be considered? Yes. These principles of programming should be considered in EVERY program you write and in the following order. 1) Readability Many programs will require modification by you or another coder in the future. A poorly written program can take more time to read and understand than the actual modification. Programs should be written in a way that is easy to comprehend quickly. This includes the following practices: a) define your variables at the top of methods b) comment your code c) use algorithms that are easy to understand. For example, avoid nested ternary operators. 2) Reusability Avoid duplicating code. Always write reusable methods instead. If a modification needs to be made, it then only has to be made in one location. 3) Efficiency When time permits, write algorithms that minimize the use of RAM and CPU time. For example, if you have nested for loops, does each loop need to run n times, or can the inner loop run fewer times? 4) Elegance Elegance is very subjective. However, some things are clear. Read Programming is an Art.
- Copy and paste this code into a text editor.
- Format it according to the criteria listed above, and the Java coding conventions.
- Change computers with an assigned partner and assess their work /10, take one mark of for each mistake.
/******************************* Author: Some Badcoder Date: Sept 15, 2022 ********************************/ 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
Complete the program below.
/* Complete the program below: * Name: User Info Validator * Date: Feb 26, 2025 * Author: You * Purpose: Ask the user for their name and age, validate it, * and display in the console. */ import java.util.Scanner; public class UserInfoValidator { public static void main(String [] args) { Scanner input = new Scanner(System.in); String name = ""; int age = 0; System.out.println("Welcome to the User Info Validator!"); name = getName(input); /* Fill in missing code here */ input.close(); } // main // Get and validate the user's name public static String getName(Scanner input) { String name; do { System.out.print("Please enter your name (at least 2 characters): "); name = input.nextLine(); } while (name.length() < 2); return name; } // getName // Get and validate the user's age public static int getAge(Scanner input) { /* Fill in the method body here */ } // getAge // Display the final result public static void displayResult(String name, int age) { System.out.println("Thank you, " + name + ". Your age is recorded as " + age + "."); } // displayResult } // class
Upcoming Assignment 1 Preview
In the next assignment, you will build on previous exercises using methods you've already worked with. Skeleton code will be provided to help you get started.
Requirements:
- You will need to use methods from previous assignments and quizzes.
- Allowed resources include your personal, non-shared notes, the Java API, and any code from earlier assignments and quizzes in this course.
- No other external resources are permitted.
Assessment Criteria:
- Code Quality: Commenting, formatting, and overall efficiency of your code.
- Design: How well your program is structured and how effectively it solves the problem.
- User Experience: Ensuring the program is easy and clear for users to interact with.
- Correctness: Meeting all requirements and producing the correct output for all test cases.
Test Cases: You will be evaluated on how your program handles the following situations:
- The user clicks Cancel during input.
- Invalid values are entered.
- Valid dates are processed correctly.
- Invalid dates are handled appropriately.
- All topics in this unit will be covered
- 25 multiple choice questions
- closed everything