Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Java review and more. Class Header  Public class Welcome  Case sensitive  Body of the class must be enclosed by braces."— Presentation transcript:

1 Java review and more

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

3 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

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

5 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)

6 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

7 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

8 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

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

10

11 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

12 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

13 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

14

15

16 Catch an exception Throw an exception

17 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

18 Repetition Structure

19 The getSales() method

20 The getCode() method

21 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

22

23 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

24 The getComm() Method

25 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

26

27 The output() method

28 The finish() method Exits system when program completes successfully

29 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];

30 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++)

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

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

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

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

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

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

37 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 + " " );

38 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( " " ); 

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

40 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”);

41 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”);

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

43 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”

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

45 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

46 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 + " " );


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

Similar presentations


Ads by Google