Java Review Most of these slides are based on

Slides:



Advertisements
Similar presentations
Chapter 1: Computer Systems
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Chapter 5 Selection Statements. Topics Controlling program flow selection –if –switch Boolean expressions –boolean primitive type –comparison operators.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Animated Version.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to Implement a selection control.
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Selection Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter Chapter 5 Selection Statements. Objectives Understand selection control statement –if statements –switch statements Write boolean expressions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
SE-1020 Dr. Mark L. Hornick 1 The switch statement int gradeLevel = kbd.nextInt(); // can be byte or short also, but not long switch( gradeLevel ) { //
Introduction to Java Java Translation Program Structure
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Most of these slides are based on “Intro to.
Chapter 5: Objectives After you have read and studied this chapter, you should be able to Implement a selection control using if statements Implement a.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides.
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.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Most of these slides are.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
Repetition Statements
CompSci 230 S Programming Techniques
Information and Computer Sciences University of Hawaii, Manoa
Chapter 4: Control Structures I
Java Language Basics.
Working with Java.
Data Types Variables are used in programs to store items of data e.g a name, a high score, an exam mark. The data stored in a variable is entered from.
Unit 3 Lesson 9 Repetition Statements (Loops)
The switch Statement, and Introduction to Looping
Chapter 5: Control Structures II
Loop Structures.
Chapter 5: Control Statements
Repetition-Counter control Loop
Java Programming: Guided Learning with Early Objects
Chapter 5: Control Structures II
Boolean Expressions And if…else Statements.
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.
Building Java Programs
Building Java Programs
Building Java Programs
Looping and Repetition
Starting JavaProgramming
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Chapter 1: Computer Systems
Building Java Programs
Chapter 6: Repetition Statements
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Java Review Most of these slides are based on
Repetition Statements (Loops) - 2
Building Java Programs
Chapter 6 Selection Statements
Building Java Programs
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
CprE 185: Intro to Problem Solving (using C)
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Looping and Repetition
Presentation transcript:

Java Review Most of these slides are based on Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files We will study two forms of repetition statements in this lesson. They are while and do-while statement. Most of these slides are based on “Intro to OOP with Java” text book by C. Thomas Wu

Java Translation The Java compiler translates Java source code into a special representation called bytecode in the .class file Java bytecode is not the machine language for any specific CPU Another software tool, called an interpreter (in our case the Java Virtual Machine), executes the bytecode Java is considered to be architecture-neutral The Java compiler is not tied to any particular machine In Chapter 5, we studied selection control statements. We will study in this chapter the second type of control statement, a repetition statement, that alters the sequential control flow. It controls the number of times a block of code is executed. In other words, a block of code is executed repeatedly until some condition occurs to stop the repetition. There are fundamentally two ways to stop the repetition—count-controlled and sentinel-controlled.

Program Structure // comments about the class public class MyProgram { } // comments about the method public static void main (String[] args) { } method header method body

Arithmetic Operators Intro to OOP with Java, C. Thomas Wu

Operator Precedence Rules The precedence table shows the order of operator evaluation. Instead of memorizing this table, it is more convenient and the code more readable if you use the parentheses judiciously.

Syntax for the if Statement if ( <boolean expression> ) <then block> else <else block> Boolean Expression Can be visualized as a flowchart if ( testScore < 70 ) JOptionPane.showMessageDialog(null, "You did not pass" ); else JOptionPane.showMessageDialog(null, "You did pass " ); Then Block Else Block Indentation is important!

Comparing Objects With primitive data types, we have only one way to compare them, but with objects (reference data type), we have two ways to compare them. We can test whether two variables point to the same object (use ==), or We can test whether two distinct objects have the same contents. String str1 = new String("Java"); String str2 = new String("Java"); if (str1 == str2) { System.out.println("They are equal"); } else { System.out.println("They are not equal"); } When we use the equality operator (==), we can comparing the contents of the variables str1 and str2. So str1 == str2 being true means the contents are the same, which in turn, means they are pointing to the same object because the content of a reference data type is an address. Therefore, if there are two distinct objects, even the values hold by these objects are the same, the equality testing by the equality operator will always result in false. Discussion of some string methods

Syntax for the switch Statement switch ( <arithmetic expression> ) { <case label 1> : <case body 1> … <case label n> : <case body n> } Arithmetic Expression switch ( gradeLevel ) { case 1: System.out.print("Go to the Gymnasium"); break; case 2: System.out.print("Go to the Science Auditorium"); case 3: System.out.print("Go to Harris Hall Rm A3"); case 4: System.out.print("Go to Bolt Hall Rm 101"); } Case Label This is the general syntax rule for a switch statement. The case body may contain zero or more statements. Case Body

Syntax for the while Statement while ( <boolean expression> ) <statement> Boolean Expression while ( number <= 100 ) { sum = sum + number; number = number + 1; } Here’s the general syntax of a while statement. As long as the <boolean expression> is true, the loop body is executed. Notice that the loop body may not be executed at all. Statement (loop body)

Example: Testing Input Data String inputStr; int age; // Create a Scanner object to read input. Scanner keyboard = new Scanner(System.in); keyboard.useDelimiter(System.getProperty("line.separator")); System.out.println(“Please enter your age (between 0 and 130):"); age = Integer.parseInt(keyboard.nextLine()); while (age < 0 || age > 130) { System.out.println("An invalid age was entered. Please try again."); } Here's a more practical example of using a repetition statement. This code will only accept a value greater than 0 but less than 130. If an input value is invalid, then the code will repeat until the valid input is read. Notice that the 'age' variable must have a value before the boolean expression of the while statement can be evaluated. We therefore read the input value before the while test. This reading of input values before the test is called priming read. The loop body of this while statement is executed zero times if the input is valid the first time.

Syntax for the do-while Statement while ( <boolean expression> ) ; do { sum += number; number++; } while ( sum <= 1000000 ); Statement (loop body) Here’s the general syntax of a do-while statement. As long as the <boolean expression> is true, the loop body is executed. Notice that the loop body is executed at least once. Boolean Expression

Syntax for the for Statement for ( <initialization>; <boolean expression>; <increment> ) <statement> 4) Increment and back to 2) 1) Initialization 2) Boolean Expression for ( i = 0 ; i < 20 ; i++ ) { number = scanner.nextInt(); sum += number; } This shows the general syntax for the for statement. The <initialization> component also can include a declaration of the control variable. We can do something like this: for (int i = 0; i < 10; i++) instead of int i; for (i = 0; i < 10; i++) 3) (loop body)

Defining a Class class { } Import Statements Class Comment Class Name Data Members Methods (incl. Constructor) This is the template we use when creating programmer-defined classes.

Creating a Package The following steps illustrate the process of creating a package name company that includes the Employee class. 1. Include the statement package company; as the first statement of the source file for the Employee class. 2. The class declaration must include the visibility modifier public as public class Employee { ... } 3. Create a folder named company, the same name as the package name. In Java, the package must have a one-to-one correspondence with the folder. 4. Place the modified Employee class into the company folder and compile it. 5. Modify the CLASSPATH environment variable to include the folder that contains the company folder. 6. Include the statement import company.* in the driver class : EmployeePayRaise

Arrays of Primitive Data Types What is an Array? Why do we need them? Array Declaration <data type> [ ] <variable> //variation 1 <data type> <variable>[ ] //variation 2 Array Creation <variable> = new <data type> [ <size> ] Example double[ ] rainfall; rainfall = new double[12]; Variation 1 double rainfall [ ]; rainfall = new double[12]; Variation 2 As you can declare and create objects in one statement such as Person p = new Person( ); you can declare and create an array in one statement as double[ ] rainfall = new double[12]; Strictly speaking, an array is a reference data type and really an object because there is no class called Array in Java. The thumbnail note in page 413 is therefore not 100 percent accurate. An array is like an object!

Array Processing double[] rainfall = new double[12]; String[] monthName = new String[12]; monthName[0] = "January"; monthName[1] = "February"; … double annualAverage, sum = 0.0; for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble(keyboard.nextLine()); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The same pattern for the remaining ten months. This code also computes the average annual rainfall, but this time we use the second array, an arrray of String so the prompt becomes "Rainfall for January", "Rainfall for February", and so forth. Notice how the monthName array is used in the for loop.

Javadoc and Java Style General information on javadoc is located at http://www.oracle.com/technetwork/java/javase/documentation/index-jsp-135444.html Java Style Specifics http://geosoft.no/development/javastyle.html

Files Reading Files Scanner inputStream = null; Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); inputStream = new Scanner(new FileInputStream(inputFileName)); String line = null; while (inputStream.hasNextLine( )) { line = inputStream.nextLine( ) }

Files (cont’d) Writing Files PrintWriter outputStream = null; System.out.print("Output file: "); String outputFileName = console.next(); outputStream = new PrintWriter( new FileOutputStream(outputFileName)); String line = null; while (inputStream.hasNextLine( )) { line = inputStream.nextLine( ); outputStream.println(count + ":" + line); }

Files (cont’d) Make sure to close the file streams when done inputStream.close( ); outputStream.close( );