04CrashCourseInJava2x
Download
Report
Transcript 04CrashCourseInJava2x
Crash Course in Java
Continues
Exceptions
• can be checked or unchecked exceptions
• checked exceptions
– caused by external conditions beyond the programmers control:
• IOException
• FileNotFoundException
• unchecked exceptions
– generally the programmer's fault
• NullPointerException
• There are many of each kind and they will be identified as
we encounter constructs where they are a problem.
• Exception should be handled using try...catch
• You can specify your own exceptions (we will see this later)
More on Exceptions
• Exceptions are thrown
– public static void main(String [] args) throws
IOException{ ... }
• Use a try block to attempt the action that
throws the exception
– try { in = new FileReader(filename);}
• Use a catch block to handle the exception
– catch (IOException ex) {ex.printStackTrace();
//take corrective action }
File I/O
public static void main(String[] args)
throws IOException , FileNotFoundException {
FileReader input;
....
try{
input = new FileReader("data.txt");
str = input.nextLine();
}
catch (FileNotFoundException ex){
System.out.println("File does not exist.");
System.exit(0);
}
catch (IOException ex){
ex.printStackTrace();
System.exit(0);
}
......
}
// we will see more of these as we go
Lab Time:
• Files and Exceptions Exercise: Work along
with me.
• Start NetBeans
• Create a New Project called
FilesAndExceptions using a package
• Browse to your usb/NetBeans Projects
directory and create the project
Create a data file
•
•
•
•
•
•
From Windows Explorer:
navigate to the FilesAndExceptions directory.
right-click in the blank area of the window
choose New | Text Document
Name it data.txt
Edit data.txt and type in the following lines or any four
names you wish
John Lennon
Paul McCartney
Ringo Starr
George Harrison
• Save the file
Return to Netbeans
• Below the JavaDoc with the @author tag type
the following:
import java.io.*;
import java.util.Scanner;
• Add the exception to the main method header
public static void main(String[] args)
throws FileNotFoundException {
The Main Method
Scanner in = null;
String first, last;
boolean everythingOK = true;
try{
in = new Scanner(new FileReader("data.txt"));
}
catch(FileNotFoundException ex){
System.out.println("File not found.");
everythingOK = false;
}
Main Method Continues
if (everythingOK)
while(in.hasNext()){
first = in.next();
last = in.next();
System.out.println(last + ", " + first);
}
else
System.out.println("bye");
}
}
Run it
• hands up if you need help
If … else
• if … else
• Syntax:
if
(BooleanExpression)
Statement1;
else
Statement2;
• Symantics:
• If BooleanExpression is true, execute Statement1; otherwise,
execute Statement2.
if
(num1 > num2)
System.out.println ("Larger one:" + num1);
else
System.out.println ("Larger one:" + num2);
If … else if … else
Switch
• The switch statement provides an alternative to nested if/else statements.
• Syntax:
switch
(switch-expression){
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-fordefault;
}
While Loop
while (loop-continuation-condition){
stmt;//Loop body
}
•
•
•
•
•
•
•
•
Semantics:
1. Evaluate the condition.
2. If condition is true
execute body of loop
go to step 1
3. If condition is false
the loop terminates and the next statement after the
while loop is executed
Do… while
• The do-while loop is very similar to the while loop, except
that the test is made at the bottom of the loop.
• Syntax:
do{
statement;
} while (cond);
nextStatement;
• Semantics:
• Execute the statement/body.
• Check cond – if true, execute body and recheck
•
otherwise, go on to nextStatement
For Loop
• Syntax:
for (init_Action; boolean_expression; update_action)
stmt;
next_stmt;
•
•
•
•
•
•
•
•
where stmt can be a compound statement.
Symantics:
1. Execute initializing action.
2. Evaluate the boolean expression
3. If the boolean expression is true then execute body of loop;
Else exit loop
4. Execute update action
5. Repeat from step 2.
primitives vs objects
• we know that primitive data values are stored in
memory locations associated with the variable
names.
• in Java, all objects are stored in the "heap" and
the starting address of the object is stored in the
memory location associated with the variable
name.
• All primitives are pass by value.
– However, we can use Integer or Double objects to
accomplish desired side-effects.
• All objects are pass by reference.
Arrays
• An array is a data structure that represents a collection
of the same type of data (homogeneous data).
• Declaring an array:
datatype[] arrayRefVar;
Example:
//declare an array of double
// named myList
double[] myList;
Declaring the array does NOT create it.
We can declare and create in one step
for primitive elements.
datatype[] arrayRefVar =
new datatype[arraySize];
double[] myList = new double[10];
The length attribute
• Array variables have a built in attribute name
that can be used to find how many things the
array can hold.
int[] list = { 3, 2, 5, 7 };
for(int i = 0; i < list.length; i++)
System.out.println(list[i]);
For this array list.length is 4
Foreach loop
• You can iterate through a full array using a
different version of the for loop
for (int element : list)
System.out.println(element);
• Will print out the contents of the array list
• The datatype refers to the datatype of the
element in the list not the index.
2-D Arrays
• Create array elements by telling how many ROWS and
COLUMNS
• Example:
int [][]grades = new int[5][3];
grades is a two-dimensional array, with 5 rows and 3 columns.
One row for each student. One column for each test.
Java arrays are row major, which means that we always refer
to the row first.
Declare, create, initialize
• Example:
int[][] grades =
{ { 78, 83, 82
{ 90, 88, 94
{ 71, 73, 78
{ 97, 96, 95
{ 89, 93, 90
},
},
},
},
} };
A Two-D Array is an array of arrays.
Each row is itself a One-D array.
Length attribute with 2-D arrays
• Use grades.length to tell you how many
rows in the 2D array.
• Use grades[0].length to tell you how
many columns in the 2D array.
Packages
• a package is a collection of associated classes
• we import packages to use them in our
programs and classes
• we can create a package for a class and import
it into whatever program we need it in
– remember that part of our goal is reuse.
• an existing package can be added to a project
simply by copying the directory to the new
project.
Java Strings
•
•
•
•
•
A Java String is an object
Once created, Java Strings are immutable
Java Strings are implemented as char arrays
Strings can be concatenated using the + operator
There are several useful methods of the String class:
– charAt(n) returns the character at the nth position in the
String
– Integer.parseInt(str) returns the Integer version of the
String str as an object
– Double.parseDouble(str) returns the Double version of the
String str as an object
• unchecked numberFormatExecption is thrown
Methods
• All methods exist inside classes
• For each application there is one and only one
– public static void main(String [] args)
• Methods are either inside packages associated with a
class or they are in the project file with the main
method.
• Methods within classes are called instance methods.
• Void methods
public void foo(args)
• Value returning methods
public dataType foo(args)
Static?
• A method or member variable can be declared
static
• That means that only one copy of it exists
• Think about a class of "space invaders" where the
objects are randomly created and some are
destroyed. A static "count" would keep track of
how many aliens are in the game at any one time.
• Main is static, because there is only one per
program.
• Static should be used carefully... if at all.
Random Numbers in Java
Random generator = new Random();
for (int i = 0; i < 10; i++)
System.out.println(generator.nextInt());
for (int i = 0; i < 10; i++)
System.out.println(generator.nextDouble());
generator.nextInt(10000);
would generate numbers between 0 and 9999
ArrayLists
• ArrayLists hold objects. Not primitives
• ArrayList<String> countries = new
ArrayList<String>();
• use countries.add("Belgium") to add an element to the end of
the list
• countries.size() returns the count of elements
• countries.get(i) returns the element at the ith position
• can use the for..each loop to iterate through the list
• use the set method to overwrite an existing element
countries.set(1,"Germany");
• use the remove method to take an element out of the list
countries.remove(2);
• If you access a nonexistant node an IndexOutOfBoundsException
is thrown.
• inserting into the middle of the list is inefficient.
LinkedLists
• Linked lists hold only objects. Not primitives.
• offer efficient means of inserting into the middle of the
list. But, it's not as simple
ListIterator<String> iterator =
countries.listIterator();
while (iterator.hasNext())
{
String country = iterator.next();
System.out.println(country);
}
Inserting/removing in a LinkedList
iterator = countries.listIterator;
iterator.next();
iterator.add("France");
.......
iterator = countries.listIterator;
iterator.next();
iterator.next();
iterator.remove();
Built in Sorts
• This is easy with arrays, linked lists, or array
lists that contain simple objects or primitives.
• for an array use
Arrays.sort(myArray);
• for an ArrayList or a LinkedList use:
Collections.sort(myList);
• for more complex objects we will write our
own sorts that use one field in the object as
our sort key.
Built in Searches
• Collections have built in searches as well...
• From the API – Collections is a class provided
by java.util
• Let's look at the API:
• http://docs.oracle.com/javase/7/docs/api/
Programming Style
• Class names always start with capital letters
• constant names are always in all caps
• it is common to prefix a boolean with the word is
– isFound
• There are two styles for braces – you may used
either one that seems good to you.
• Be aware that NetBeans will close parentheses,
curly braces and quotes automatically and it
spaces the closing curly brace correctly.
Java API
• The JavaDoc documentation of the entire java
language.
• http://docs.oracle.com/javase/7/docs/api/
• Need to learn how to write JavaDoc
documentation.
• Need to learn how to read JavaDoc
documentation.