CS 0401 Debugging Hints and Programming Quirks for Java by John C. Ramirez University of Pittsburgh.

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Repetition – Do Loops.
Advertisements

Loops (Part 1) Computer Science Erwin High School Fall 2014.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
The switch Statement, DecimalFormat, and Introduction to Looping
5.05 Apply Looping Structures
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
© 2004 Pearson Addison-Wesley. All rights reserved February 20, 2006 ‘do’ and ‘for’ loops ComS 207: Programming I (in Java) Iowa State University, SPRING.
Chapter 5 Loops.
Week 4 - Monday.  What did we talk about last time?  Wrapper classes  if statements.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
The for loop.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
Topic : While, For, Do-While Loop Guided By : Branch : Batch :
Discussion 4 eecs 183 Hannah Westra.
Lecture 4b Repeating With Loops
CprE 185: Intro to Problem Solving (using C)
Chapter 4 Repetition Statements (loops)
Chapter 5: Control Structures II
Loop Structures.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Lecture 07 More Repetition Richard Gesick.
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Loops CIS 40 – Introduction to Programming in Python
Java Programming Control Structures Part 1
3.5- The while Statement The while statement has the following syntax:
ECE 103 Engineering Programming Chapter 18 Iteration
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
‘do’ and ‘for’ loops October 1, 2007 ComS 207: Programming I (in Java)
‘do’ and ‘for’ loops October 2, 2006 ComS 207: Programming I (in Java)
Presentation transcript:

CS 0401 Debugging Hints and Programming Quirks for Java by John C. Ramirez University of Pittsburgh

2 These slides may be updated throughout the term to help you with your Java programming and debugging They are more or less in the order that the problem / issue comes to my attention Be sure to refer to the textbook and regular notes for additional programming and debugging information

3 String Literals in your Program Java String literals cannot extend past the end of a line  For example, the following is illegal: System.out.println(“I am printing out a very long String so I am using two lines!”);  This is a compilation error: “unclosed string literal” Will occur on both lines in which literal appears  Note that “wrapped” lines are ok Editor may move part of a line to the next line, even though you never hit “Enter”

4 Method Variable Initialization Java method variables (i.e. variables declared within methods) are not automatically initialized  If you try to access the value of an uninitialized method variable in a Java program you will get a compilation error Error will occur even if variable “might” not be initialized Ex: int i, j; j = 3 * i; –“variable i might not have been initialized”

5 Method Variable Initialization Ex: int max; String ok; System.out.println(“Do you want to continue? (y/n)”); ok = inScan.next(); // inScan is a legal Scanner if (ok.equals(“y”)) { System.out.println(“Enter max value”); max = inScan.next(); } System.out.println(“Max is “ + max); Still gives the error since if condition could be false

6 Infinite Loops Recall the while loop syntax while (booleanExpression) loop_body; // Java statement, which could // be a block  A common problem with while loops (and loops in general) is the infinite loop Loop condition is never false  This can occur for many reasons, but a common one for intro programmers is a neglect to update the components of booleanExpression within the loop body If expression doesn’t change, it will never be false

7 Infinite Loops Ex: int count = 1, max = 10, sum = 0; while (count <= max) { sum += count; } System.out.println(“Sum is “ + sum); Within loop, count does not change and neither does max –Therefore, once true the condition will never be false Luckily, infinite loops are relatively easy to detect –Program runs much longer than it should –Output is repeated over and over

8 Entry Loop Programming Recall that entry loops test a condition to get into the loop body  Repeats this test prior to each iteration  When user input determines if loop should continue or not, we can generalize the behavior as: READ (read an initial value from the user) TEST (the loop entry condition) PROCESS (the loop body if the condition was true) READ (read the next value from the user)  Note that the first READ is OUTSIDE of the loop LOOP BODY

9 Entry Loop Programming The idea is that we initially have to “set” the entry condition prior to the loop We then have to “reset” it at the end of the loop body, so it can be tested again for the next iteration Ex: System.out.println(“Enter a pos. num.”); int num = inScan.nextInt(); while (num > 0) { System.out.println(“You entered “ + num); System.out.println(“Enter a pos. num.”); num = inScan.nextInt(); } System.out.println(“Good-bye”);

10 Declaration Within Blocks As we discussed in lecture, the scope of method variables is the point in the block where they are declared to the end of that block Ex: { // bunch of statements int i; // bunch more statements } SCOPE OF i

11 Declaration Within Blocks  When you have nested control structures, it is fairly common to declare variables within a block such as a loop body  Be careful to note that any variables declared within an inner block (such as an inner loop or inner if statement) will NOT be accessible once that block terminates Note that this applies to variables declared in the headers of for loops!!!  If there is any doubt, declare your variables in the outermost block of your method

12 Declaration Within Blocks for (int i = 0; i < 10; i++) { System.out.println(“i is “ + i); } System.out.println(“i is “ + i); // ERROR System.out.println(“Enter two numbers”); int one = myScanner.nextInt(); int two = myScanner.nextInt(); if (one >= two) { int max = one; } else { int max = two; } System.out.println(“Max is “ + max); // ERROR

13 Accidentally Declaring a Variable Twice Java variables can be declared only one time within a block (or a nested subblock)  It you redeclare the same variable, the compiler will give you an error: varname is already defined in …  A common way to get this error is via “copy and paste” You declare and assign the variable in one statement in some part of your code You want to use it again somewhere else, so you copy and paste the code (including the declaration) However, only the assignment should be copied!

14 Accessing a null Reference Variable Java reference variables are used to access objects and their instance methods If we have not yet assigned an object to a variable, we typically initialize it to null  This means that the variable exists but no object yet exists The reference does not point to anything Ex: String S = null; S

15 Accessing a null Reference Variable  However, instance methods are associated with Objects Thus, if the object does not exist, the methods cannot be called  A common error in Java is an attempt to call an instance method from a null reference Ex: String S = null; if (S.equals(“Wacky”)) System.out.println(“This is wacky!”); else System.out.println(“Not wacky!”); Note that the result of this is NOT “Not wacky!” Rather it is an error because the instance methods do not even exist

16 Accessing a null Reference Variable We cannot call S.equals() since there is no object referred to by S The error will be an exception, occurring during run- time: java.lang.NullPointerException This is because the compiler cannot know if an object will exist or not, so it cannot check the error But when the method is actually called during execution, the interpreter discovers that no object exists (i.e. the reference is null)  Be careful to recognize this error – it is very common!

17 Comparing References vs. Objects A common logic error is that of comparing references when you mean to compare objects  We know that the == operator is used to compare primitive types  This operator also works with reference types, but it compares the references, NOT the data within the objects that they refer to To compare the data in the objects, we need to call a method, typically the equals() method –Actual comparison depends on how equals() is implemented in a given class

18 Comparing References vs. Objects  For example: String S1, S2, S3; S1 = new String(“Wacky”); S2 = new String(“Wacky”); S3 = S1; if (S1 == S3) { System.out.print(“Same reference means the “); System.out.println(“same physical object”); } if (S1 != S2) { System.out.print(“Not the same reference / object “); System.out.println(“even though the data is the same”); } if (S1.equals(S2)) { System.out.println(“Same data in different objects”); }