Some coding issues Statement groups, semi-colons and ifs.

Slides:



Advertisements
Similar presentations
1 CS101 Introduction to Computing Lecture 23 Flow Control & Loops (Web Development Lecture 8)
Advertisements

Lecture Roger Sutton CO331 Visual programming 15: Debugging 1.
Homework Any Questions?. Statements / Blocks, Section 3.1 An expression becomes a statement when it is followed by a semicolon x = 0; Braces are used.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Grouping Objects 2 Collections and the for-each loop Collections and the while loop.
Grouping Objects 1 Introduction to Collections.
28-Jun-15 Recognizers. 2 Parsers and recognizers Given a grammar (say, in BNF) and a string, A recognizer will tell whether the string belongs to the.
Modul 3 Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Created by NW 2012 – please note all copyright on images used is property of copyright holder. Note: some of the more complicated descriptions are taken.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CPS120: Introduction to Computer Science Decision Making in Programs.
CIS 234: Control Structures - Selection Dr. Ralph D. Westfall April, 2010.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout
Grouping objects Introduction to collections 5.0.
CPS120: Introduction to Computer Science Decision Making in Programs.
PHY281Flow ControlSlide 1 Decisions In this section we will learn how to make decisions in a Java program  if Statements  if... else Statements  Comparison.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
1 Programming Week 2 2 Inheritance Basic Java Language Section.
Agenda Basic Logic Purpose if statement if / else statement
VARIABLES Programmes work by manipulating data placed in memory. The data can be numbers, text, objects, pointers to other memory areas, and more besides.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Copyright © Curt Hill The IF Revisited If part 4 Style and Testing.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Error Handling Tonga Institute of Higher Education.
Grouping objects Introduction to collections 5.0.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Variables  A piece of memory set aside to store data  When declared, the memory is given a name  by using the name, we can access the data that sits.
CPS120: Introduction to Computer Science Decision Making in Programs.
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
Java Programming Fifth Edition Chapter 1 Creating Your First Java Classes.
IF STATEMENTS AND BOOLEAN EXPRESSIONS. BOOLEAN EXPRESSIONS Evaluate to a value of true or false Use relational or equivalence operators Boolean operators.
CCSA 221 Programming in C CHAPTER 3 COMPILING AND RUNNING YOUR FIRST PROGRAM 1 ALHANOUF ALAMR.
11 Making Decisions in a Program Session 2.3. Session Overview  Introduce the idea of an algorithm  Show how a program can make logical decisions based.
Lab 4: Loops and Iteration Graham Northup
Chapter 7: User-Defined Functions II
Week 3 - Friday CS222.
Variables A piece of memory set aside to store data
User-Defined Functions
Conditions and Ifs BIS1523 – Lecture 8.
Introduction to C++ Programming
Homework Any Questions?.
Controlling Program Flow
Presentation transcript:

Some coding issues Statement groups, semi-colons and ifs

If you can keep your head when all about you are losing theirs, it's just possible you haven't grasped the situation.

Some coding issues... Be careful with { statement grouping brackets } and semi-colons; Every statement and declaration ends with a semi-colon; ; In Java, writing nothing also counts as a statement; This line; is a sequence;;; of six; “statements”;

An if-construct starts with an if, then a (condition in round brackets ), then a statement; or {group of statements} Optionally, an if-construct may continue with an else, followed by a statement; or {group of statements} In Java:

An if-construct starts with an if, then a (condition in round brackets ), then a {group of statements} Optionally, an if-construct may continue with an else, followed by a {group of statements} { } However, we recommend always to use a {group of statements} for the statement parts … i.e. {} ; … even if the {group of statements} contains only a single statement;

/** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() == 0); { System.out.println("Notebook is empty"); } else { System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); } } What’s wrong here?

/** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() == 0); { System.out.println("Notebook is empty"); } else { System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); } } This is a complete if-construct with an empty statement, . Code layout is necessary to aid readability by reflecting code structure – unfortunately, the above layout reflects only our intention … and not the actual structure written!

This is a complete if-construct with an empty statement, . If the condition is true (i.e. the notebook is empty), an empty statement is executed (which does nothing). So, nothing is done, regardless of whether the condition is true or not! /** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() == 0); { System.out.println("Notebook is empty"); } else { System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); } }

Here is a statement-group … it has only one statement (which is OK and happens quite a lot). It is executed after that (useless) if-construct, regardless of whether the condition was true or not!

/** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() == 0); { System.out.println("Notebook is empty"); } else { System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); } } Here is an else-statement-group that is part of no if-construct. This is illegal and will not compile!

/** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() == 0); { System.out.println("Notebook is empty"); } else { System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); } } This is a complete if-construct with an empty statement, . Get rid of the semi-colon …

/** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() == 0) { System.out.println("Notebook is empty"); } else { System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); } } We now have a legal if-construct. The first statement-group is executed if the condition is true. The second statement-group is executed if the condition is false. We now have a legal if-construct. The first statement-group is executed if the condition is true. The second statement-group is executed if the condition is false.

/** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() = 0) { System.out.println("Notebook is empty"); } else { System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); } } This is an (illegal) assignment statement, . Be careful not to confuse == (which is the test-for-equality symbol) with = (which is the assignment symbol). The above code has an assignment statement where it should have a condition. This is illegal.

/** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() == 0) { System.out.println("Notebook is empty"); } else { System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); } } Back to our legal if-construct. There is another way to express the same logic …

/** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() == 0) { System.out.println("Notebook is empty"); return; } System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); } This if-construct has no else-part and is legal. If the condition is true, the statement-group is executed … and this contains a return statement (which immediately exits the method). If the condition is false, the if-construct is finished and the statements following it are executed.

However, this is a little clever … on the whole, we prefer expressing the alternatives explicitly … /** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() == 0) { System.out.println("Notebook is empty"); return; } System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); }

/** * Print out notebook info (number of entries). */ public void showStatus() { if(notes.size() == 0) { System.out.println("Notebook is empty"); } else { System.out.print("Notebook holds "); System.out.println(notes.size() + " notes"); } } … as we had before. … as we had before.

/** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */ public void addNote(String note) { if(notes.size() == 100) notes.save(); // starting new notebook notes = new ArrayList (); notes.add(note); } What’s wrong here?

This is a complete if-construct with a single statement, . /** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */ public void addNote(String note) { if(notes.size() == 100) notes.save(); // starting new notebook notes = new ArrayList (); notes.add(note); } Oh dear, we forgot the curly brackets …    … correct layout for the above logic (which we don’t want) would be:

This is a complete if-construct with a single statement, . /** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */ public void addNote(String note) { if(notes.size() == 100) notes.save(); // starting new notebook notes = new ArrayList (); notes.add(note); } In the above, if the condition is true, save the notes. Whether the condition is true or false, start a new notebook …   

This is a complete if-construct with a single statement, . /** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */ public void addNote(String note) { if(notes.size() == 100) notes.save(); // starting new notebook notes = new ArrayList (); notes.add(note); } Let’s try again … this time, we add in the curly brackets so that the logical structure matches the layout:

This is a complete if-construct with a statement-group, . /** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */ public void addNote(String note) { if(notes.size() == 100) { notes.save(); // starting new notebook notes = new ArrayList (); } notes.add(note); } Now, the logical structure of the if-construct matches its layout. Now, the logical structure of the if-construct matches its layout.

Always write your code as if the guy who ends up maintaining it will be a violent psychopath who knows where you live … Be careful with { statement grouping brackets } and semi-colons; Always use { statement-groups } for the actions dependent upon the ( condition ) in an if-construct.

Debugging Using the BlueJ debugger (section 3.12) Concepts Only when all else fails – i.e. not as a first resort! First resort: read your code! Why should it work … not why doesn’t it work?!! Explain to a friend. First resort: read your code! Why should it work … not why doesn’t it work?!! Explain to a friend.