Java review and more

Download Report

Transcript 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
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^311
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 23-24
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 < 13) || (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











<!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>
JavaScript
Extension of java code—except read in
browser
 Why is javascript better than an applet?

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>
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>
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>
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>
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>" );
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>
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


Else


Print “Failed”
If ( studentGrade >= 60)


Print “Passed”
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



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 “A”
Print “C”
Else

Print “F”
The Compound Else Statement

if (grade >= 60)


document.writeln( “ Passed”);
else {



document.writeln( “Failed <BR>”);
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(
"<H1>Class average is " + average + "</H1>" );