Java review and more. Class Header  Public class Welcome  Case sensitive  Body of the class must be enclosed by braces.

Slides:



Advertisements
Similar presentations
Types of selection structures
Advertisements

Java Programming, 3e Concepts and Techniques Chapter 3 Section 63 – Manipulating Data Using Methods – Day 2.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
 Control structures  Algorithm & flowchart  If statements  While statements.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
 2001 Deitel & Associates, Inc. All rights reserved. 1 Outline 14.1Introduction 14.2Algorithms 14.3Pseudocode 14.4Control Structures 14.5The if Selection.
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Java Programming, 3e Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
1 JavaScript/Jscript: Arrays. 2 Introduction Arrays –Data structures consisting of related data items (collections of data items) JavaScript arrays are.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - JavaScript: Control Structures I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4.
Java Programming, 2E Introductory Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Java Programming, Second Edition Chapter Five Input and Selection.
Input, Output, and Processing
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
C++ Programming Lecture 6 Control Structure II (Repetition) By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - JavaScript: Control Structures I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4.
Introduction to Java Java Translation Program Structure
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 JavaScript: Control Structures. 2 Control Structures Flowcharting JavaScript’s sequence structure.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
JavaScript, Fourth Edition
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
1 Chapter 3 – JavaScript Outline Introduction Flowcharts Control Structures if Selection Structure if/else Selection Structure while Repetition Structure.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
JavaScript 1 COE 201- Computer Proficiency. Introduction JavaScript scripting language ▫Originally created by Netscape ▫Facilitates disciplined approach.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing a Line of Text in a Web Page 7.3 Another JavaScript.
Adapted from  2004 Prentice Hall, Inc. All rights reserved. 5 th and 4 th ed: Chapters 6,7,8 SY306 Web and Databases for Cyber Operations SlideSet #6:
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control Statements: Part1  if, if…else, switch 1.
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.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
1 JavaScript/Jscript 2 Control Structures I. 2 Introduction Before programming a script have a –Thorough understanding of problem –Carefully planned approach.
INTERNET APPLICATIONS CPIT405 JavaScript Instructor: Rasha AlOmari
JavaScript: Control Structures I Outline 1 Introduction 2 Algorithms 3 Pseudocode 4 Control Structures 5 if Selection Structure 6 if/else Selection Structure.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Yanal Alahmad Java Workshop Yanal Alahmad
2.5 Another Java Application: Adding Integers
The Selection Structure
Ch 7: JavaScript Control Statements I.
Chapter 4 – Control Structures Part 1
JavaScript: Control Statements.
CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 OF 3
JavaScript: Control Statements I
Structured Program
MSIS 655 Advanced Business Applications Programming
3 Control Statements:.
2.6 The if/else Selection Structure
Presentation transcript:

Java review and more

Class Header  Public class Welcome  Case sensitive  Body of the class must be enclosed by braces

Method Header  Modifier return datatype methodname (datatype parameter)  Public static void main (String [] args)  Public—other classes may invoke method  Static—unique and can be invoked without a subclass  Return value (void) is result or answer—void means method does not return data  Parentheses enclose a list of parameters used by method  Includes data type (string) and identifier (args)  Both class and methods need to have brackets to start and end

Importing packages  Some classes and methods are not immediately available and must be imported  Java.applet  Java.awt  Java.io  Java.lang  Java.util

Java formatting  \t horizontal tab (8 spaces to the right)  \b backspace (1 space to the left)  \n new line (moves insertion point down 1 line and to the left margin)  \r carriage return (moves insertion point to the left margin)

Java primitive data types  Boolean (data stored as one of two states)  Byte stores whole number values in 8-bit (-128 to 127)  Char  Double—numbers up to 14/15 decimal as  Float numbers up to 6/7 decimals  Int whole numbers in 32 bit from -2^31 to 2^31- 1  Long 64 bit whole number values  Short 16 bit whole number values

Buffered Reader Constructor  BufferedReader – a class from java.io package  dataIn – identifier variable  = new constructor notation (to construct instance of a class  Buffered Reader () method  InputStreamReader (a bridge from byte streams to character streams)  System.in an object representing the keyboard

Conversions  readLine() method –reads input and returns a String containing contents of input  Integer.parseInt(variablename) allows us to convert string to a variable type

The if…else Statement  Single: line 29, line 30  Block: lines 15-26, lines 19-20, lines  Nested: lines 17-25, lines 29-30

Testing with an if statement  Testing a single condition if (answer == null) if (!done)  Testing multiple conditions if ((gender == “male”) && (age >= 18)) if ((age 65)) AND and OR expressions evaluate the right operand only if the left operand is not sufficient to decide the condition

Exception Handling  An exception is an event resulting from an erroneous situation which disrupts normal program flow  Exception handling is the concept of planning for possible exceptions by directing the program to deal with them gracefully, without terminating  Two kinds of exceptions Run-time Checked  The compiler checks each method to ensure each method has a handler

Handling Exceptions  The try statement identifies a block of statements that may potentially throw an exception  The throw statement transfers execution from the method that caused the exception to the handler Transfers execution to the catch statement if the throw is placed within a try statement  The catch statement identifies the type of exception being caught and statements to describe or fix the error  The finally statement is optional and is always executed regardless of whether an exception has taken place Placed after the catch statement

Catch an exception Throw an exception

Testing methods  Compile the program after coding each method and call statement  Run the program with correct input  Run the program to test the exception handling with invalid input Alphabetic data Negative values Null or zero values  Verify that the user is allowed to reenter data  Verify the program closes correctly

Repetition Structure

The getSales() method

The getCode() method

The Case Structure  A type of selection structure that allows for more than two choices when the condition is evaluated  Used when there are many possible, valid choices for user input  The code evaluates the user choice with a switch statement and looks for a match in each case statement  Each case statement contains a ending break statement which forces exit of the structure

Arguments and Parameters  When a method is called, the calling method sends arguments; the called method accepts the values as parameters  Different but related identifier names for the arguments and the parameters should be used for good program design The variables are only visible in their respective methods  Arguments and parameters for a called method and the calling statement must be of the same number, order, and data type

The getComm() Method

Formatting Numeric Output  The DecimalFormat class formats decimal numbers into Strings for output  Supports different locales, leading and trailing zeros, prefixes/suffixes, and separators  The argument is a pattern, which determines how the formatted number should be displayed

The output() method

The finish() method Exits system when program completes successfully

Arrays  A method to stores lists of related data items and manipulate data more efficiently  An array can store multiple data items of the same type in a single memory location  Declaring arrays Int [] ages; Int ages[];  Constructing arrays Ages = new int[100]; Int [] ages = new int[100];

The For Loop  Prior a while loop was used Good for when you need to perform a task for an undetermined number of times  However, when you want to specify the exact number of times the loop will be executed– use a for  Syntax – for (int j=1; j<5; j++)

A simple javascript page   A First Program in JavaScript   document.writeln(  " Welcome to JavaScript Programming! " ); 

JavaScript  Extension of java code—except read in browser  Why is javascript better than an applet?

How you place it in your web page   Javascript goes here   You can also make an include call 

Making a simple color change   Printing a Line with Multiple Statements   document.write( " Welcome to " );  document.writeln( "JavaScript Programming! " ); 

Adding a line break   Printing Multiple Lines   document.writeln(  " Welcome to JavaScript Programming! " ); 

Alert/Dialog Box   window.alert( "Welcome to\nJavaScript\nProgramming!" );   Click Refresh (or Reload) to run this script again. 

Adding Integers w/Prompt Boxes   var firstNumber, // first string entered by user  secondNumber, // second string entered by user  number1, // first number to add  number2, // second number to add  sum; // sum of number1 and number2  // read in first number from user as a string  firstNumber = window.prompt( "Enter first integer", "0" );  // read in second number from user as a string  secondNumber = window.prompt( "Enter second integer", "0" );  // convert numbers from strings to integers  number1 = parseInt( firstNumber );  number2 = parseInt( secondNumber );  // add the numbers  sum = number1 + number2;  // display the results  document.writeln( " The sum is " + sum + " " );

Comparison Example   var first, // first string entered by user  second; // second string entered by user  // read first number from user as a string  first = window.prompt( "Enter first integer:", "0" );  // read second number from user as a string  second = window.prompt( "Enter second integer:", "0" );  document.writeln( " Comparison Results " );  document.writeln( " " );  if ( first == second )  document.writeln( " " + first + " == " + second +  " " );  if ( first != second )  document.writeln( " " + first + " != " + second +  " " );  if ( first < second )  document.writeln( " " + first + " < " + second +  " " );  if ( first > second )  document.writeln( " " + first + " > " + second +  " " );  if ( first <= second )  document.writeln( " " + first + " <= " + second +  " " );  if ( first >= second )  document.writeln( " " + first + " >= " + second +  " " );  // Display results  document.writeln( " " ); 

Control Structures  Three main types of selection structure If If/Else Switch  Four types of repetition While Do/While For For/In

The If Selection Structure  Used to choose among alternative courses of action in a program If a student’s grade is greater than or equal to 60  Print “Passed” If ( studentGrade >= 60)  document.writeln( “Passed”);

The If/Else Structure  This structure performs an indicated action only when the condition evaluates to true, otherwise the action is skipped, or it can perform a different action if false. If a student’s grade is greater than or equal to 60  Print “Passed” Else  Print “Failed” If ( studentGrade >= 60)  document.writeln( “Passed”); Else  document.writeln( “Failed”);

Conditional Operator  A special command that functions the same as the If/Else statement document.writeln(  studentGrade >= 60 ? “Passed” : “Failed” );

Nested If/Else Structures  Used to test multiple cases If student’s grade is greater than or equal to 90  Print “A” Else If student’s grade is greater than or equal to 80  Print “B” Else If student’s grade is greater than or equal to 70  Print “C” Else  Print “F”

The Compound Else Statement  if (grade >= 60) document.writeln( “ Passed”);  else { document.writeln( “Failed ”); document.writeln(“ You must take this course again”); }

The while repetition structure  A repetition structure allows the programmer to specify an action that is to be repeated while some condition remains true While there are more items on my shopping list  Purchase next item and cross off my list

The while repetition in Javascript  // Initialization Phase  total = 0; // clear total  gradeCounter = 1; // prepare to loop  // Processing Phase  while ( gradeCounter <= 10 ) { // loop 10 times  // prompt for input and read grade from user  grade = window.prompt( "Enter integer grade:", "0" );  // convert grade from a String to an integer  gradeValue = parseInt( grade );  // add gradeValue to total  total = total + gradeValue;  // add 1 to gradeCounter  gradeCounter = gradeCounter + 1;  }  // Termination Phase  average = total / 10; // calculate the average  // display average of exam grades  document.writeln(  " Class average is " + average + " " );