1 / 46

Java review and more

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

salena
Download Presentation

Java review and more

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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. Testing with an if statement • Testing a single condition • if (answer == null) • if (!done) • Testing multiple conditions • if ((gender == “male”) && (age >= 18)) • if ((age < 13) || (age > 65)) • AND and OR expressions evaluate the right operand only if the left operand is not sufficient to decide the condition

  11. 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

  12. 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

  13. Catch an exception Throw an exception

  14. 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

  15. Repetition Structure

  16. The getSales() method

  17. The getCode() method

  18. 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

  19. 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

  20. The getComm() Method

  21. 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

  22. The output() method

  23. The finish() method Exits system when program completes successfully

  24. 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];

  25. 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++)

  26. A simple javascript page • <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> • <!-- Fig. 13.1: welcome.html --> • <HTML> • <HEAD> • <TITLE>A First Program in JavaScript</TITLE> • <SCRIPT LANGUAGE = "JavaScript"> • document.writeln( • "<H1>Welcome to JavaScript Programming!</H1>" ); • </SCRIPT> • </HEAD><BODY></BODY> • </HTML>

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

  28. How you place it in your web page • <html> • <head> • <script> • Javascript goes here • </script> • </head> • <body> • </body> • You can also make an include call • <script src=“path/to/fileName.js”></script>

  29. Making a simple color change • <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> • <HTML> • <!-- Fig. 13.2: welcome.html --> • <HEAD> • <TITLE>Printing a Line with Multiple Statements</TITLE> • <SCRIPT LANGUAGE = "JavaScript"> • document.write( "<FONT COLOR='magenta'><H1>Welcome to " ); • document.writeln( "JavaScript Programming!</H1></FONT>" ); • </SCRIPT> • </HEAD><BODY></BODY> • </HTML>

  30. Adding a line break • <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> • <HTML> • <!-- Fig. 13.3: welcome.html --> • <HEAD><TITLE>Printing Multiple Lines</TITLE> • <SCRIPT LANGUAGE = "JavaScript"> • document.writeln( • "<H1>Welcome to<BR>JavaScript<BR>Programming!</H1>" ); • </SCRIPT> • </HEAD><BODY></BODY> • </HTML>

  31. Alert/Dialog Box • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> • <HTML> • <!-- Fig. 13.4: welcome.html --> • <!-- Printing multiple lines in a dialog box --> • <HEAD> • <SCRIPT LANGUAGE = "JavaScript"> • window.alert( "Welcome to\nJavaScript\nProgramming!" ); • </SCRIPT> • </HEAD> • <BODY> • <P>Click Refresh (or Reload) to run this script again.</P> • </BODY> • </HTML>

  32. Adding Integers w/Prompt Boxes • <SCRIPT LANGUAGE = "JavaScript"> • 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( "<H1>The sum is " + sum + "</H1>" );

  33. Comparison Example • <SCRIPT LANGUAGE = "JavaScript"> • 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( "<H1>Comparison Results</H1>" ); • document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" ); • if ( first == second ) • document.writeln( "<TR><TD>" + first + " == " + second + • "</TD></TR>" ); • if ( first != second ) • document.writeln( "<TR><TD>" + first + " != " + second + • "</TD></TR>" ); • if ( first < second ) • document.writeln( "<TR><TD>" + first + " < " + second + • "</TD></TR>" ); • if ( first > second ) • document.writeln( "<TR><TD>" + first + " > " + second + • "</TD></TR>" ); • if ( first <= second ) • document.writeln( "<TR><TD>" + first + " <= " + second + • "</TD></TR>" ); • if ( first >= second ) • document.writeln( "<TR><TD>" + first + " >= " + second + • "</TD></TR>" ); • // Display results • document.writeln( "</TABLE>" ); • </SCRIPT>

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

  35. 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”);

  36. 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”);

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

  38. 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”

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

  40. 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

  41. 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( • "<H1>Class average is " + average + "</H1>" );

More Related