CIS110-203 Intro to Computer Science Lab 1 - SEAS

Download Report

Transcript CIS110-203 Intro to Computer Science Lab 1 - SEAS

Intro to Computer Science
Class #8
Exceptions and I/O
Instructor: Ms. Catherine Stocker
Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison, Thibault
University of Pennsylvania
9 April 2008
Today’s Agenda
•
•
•
•
Quiz
Discussion
Exceptions
File I/O
Focused on
Cryptography
Discussion
Let’s talk about cryptography!
Introduction
• The world is full of bad (dumb ?) people wanting
to crash your program
Here come Exceptions
• The world is full of nosy people wanting to see
what you’re doing
 Here comes Cryptography
Contract
A good input, fulfilling
An incorrect input
some conditions
????
A correct output
What shall we do ?
• Any ideas on what we should do ?
–
–
–
–
Error message
Default value
Error value
Kill the user
Java provides a very efficient way of dealing
with this
Exceptions
• Already seen some of them: NullPointerException,
ArrayIndexOutOfBoundException
• An exception is:
– An object created by methods when there is a
problem.
– When this object is created, the method exits
immediately and “throws” it toward the user.
– If no methods try to catch it, it will “hit” the user and
display the error message.
Let’s throw one …
• Enough with the theory, we want to see some
red nasty errors!
> int data[] = new int[10];
> data[666] = 0;
• What will happen ?
Demo: carelessMethod
public class SimpleClass{
public int carelessMethod(int n){
int sum=0;
int i = 1;
while(i!=(n+1)){
sum+=i;
i++;
}
return sum;
}
}
My own exception
It HAS to extend Exception to be thrown
public class NegativeException extends Exception{
public NegativeException(int num){
// call the constructor of the super class
// (in this case, Exception)
super("Negative ” +num+ " not
allowed...");
}
}
Usually, we say why we caused the exception,
just by using super(). What is super() ?
How to throw one ?
public void myFunction throws
ArrayIndexOutOfBoundsException{
// Some Code
throw new ArrayIndexOutOfBoundsException();
// Some Code
}
How to throw one ?
I can also throw my own exception !
public void myFunction throws NegativeException{
// Some Code
throw new NegativeException(“something”);
// Some Code
}
Demo: carelessMethod
Or any class extending the class Exception
public class SimpleClass{
public int carelessMethod(int n) throws
NegativeException {
int sum=0;
int i = 1;
We have to declare that this method might cause
if(n<=0){
exception
throw new an
NegativeException(n);
}
Create a new
while(i!=(n+1)){
Exception and
sum+=i;
throw it
i++;
}
return sum;
}
try/catch
• Perhaps we want to fix the error ourselves …
– catch it before it reaches the user, and do something
appropriate
– Syntax: try{…}
– Syntax: catch(NegativeException n){ … }
– Don’t bother too much about these for now, catching
is used mainly for file I/O
Demo: carefulMethod
public class SimpleClass
{
public int carefulMethod(int n) throws
NegativeException {
int sum=0;
try{
sum = carelessMethod(n);
System.out.println(“All done”);
}
catch(NegativeException e){
System.out.println(“Please Try again”);
}
return sum;
}
}
Now lab…
• Go to
http://www.seas.upenn.edu/eas285/forSLA
Students/lectures/lecture8_ExceptionsIO/l
ab1.html
• Work in pairs
- Goal: LET’S CRASH OUR PROGRAMS !!
Demo: carefulMethod
public class SimpleClass
{
public int carefulMethod(int n) throws
NegativeException {
int sum=0;
try{
sum = carelessMethod(n);
System.out.println(“All done”);
}
catch(NegativeException e){
System.out.println(“Please Try again”);
}
return sum;
}
}
You know I/O. Yes, you do.
• Remember:
– System.out.println
– Used to print strings on the screen
• System.out is doing some I/O
• One major concept of I/O are streams
What is a stream ?
The Keyboard
The Screen
System.in
System.out
+
System.err
Streams
My Program
My Hard disk
What is ascii ??
Using Java Predefined Classes
• Input and Output is long, complicated, and
luckily Java has written a class that we
can use to do it !
 We will use java predefined classes
and use import
How to search for classes ?
Little demo using google
File I/O
• We need to access files:
- we can’t always rely on the user for input;
- we can’t even use the user for some input
(image processing, etc…)
- we might want to save variables for the next
use
• To access Files, we need to do a few things:
- create a File object
- create a stream to this file object
- play with the stream, write/read
- close the stream
Create a File object
• How to create an instance ? (remember: import java.io.File)
 File f = new File(“path_to_file”);
Hint: how to know your working directory ?
System.getProperty("user.dir");
Example and playing with a file object (try typing this in
Interaction Pane):
File f = new File(“my_text.txt”);
f.exists();
f.getPath();
f.length();
// For more, look on the web :)
How to read a file? FileInputStream
• How to create an instance ?
 FileInputStream fs = new FileInputStream(f);
•How to read from it ?
int i = fs.read();
• How to close it ?
 fs.close();
Important: if int i = fs.read() == -1 ; it means that wei reached
the end of the file.
66
65
A
B C
D
E
F
G H
I
J K L
How to read a file? FileInputStream
• Basic example, reading a file and printing it to the screen
import java.io.*;
File f = new File(“my_text.txt”);
FileInputStream fs = new FileInputStream(f);
int data = fs.read(); // an int because it’s the ascii code of it
while(data>=0){ // if data == -1  End of the file
System.out.write(data);
// System.out.write is printing the character
associated
//with the ascii value given as argument
data = fs.read();
}
fs.close();
More classes ?
• We can use more advanced classes:
StringBuffer : an object where we can append new characters to it, very
useful for file reading
FileReader: basically (for now) the same that FileInputStream
URL : an equivalent of the File object but for webpages, has the function
openStream() which returns an InputStream to that page, for example:
import java.net.*;
url = new URL(”http://www.google.fr“);
InputStream in = url.openStream();
int data = in.read();
while(data>=0){
System.out.write(data);
data = in.read();
}
in.close();
How to write to a file? FileOutputStream
• How to create an instance ?
FileOutputStream fs = new FileOutputStream(f,True);
// If the file exists, it will append data to the end. If the
// file doesn’t exist, it will create it.
•How to write to it ?
fs.write(i)
• How to close it ?
 fs.close();
i
65
A A
How to write to a file ? FileOutput
• Basic Example, writing “Hello world” to a text file
import java.io.*;
File f = new File(”text-file.txt”);
FileOutputStream fs = new FileOutputStream(f);
char[] c = “hello world”.toCharArray(); // What is that ??
for(int i=0;i<c.length;i++)
{
fs.write((int) c[i]); // And that ???
}
fs.close();
Now lab…
• Go to
www.seas.upenn.edu/eas285/forSLAStud
ents/lectures/lecture8_ExceptionsIO/lab2.
html
Work in pairs too
- Goal: encrypting and decrypting a string, read
from a file and writing it to the file
Why did I talk about Exceptions?
• Usually when you try to access a File, there can be
some problems (File not found, hard drive crash,
computer exploded..)
• So you use … Exceptions!
• try{
// Opening the stream
}
catch(IOException e)
{
// Well, notify the user, fix the error
}
More on encryption
http://www.di-mgt.com.au/rsa_alg.html
http://www.gax.nl/wiskundePO/#
http://en.wikipedia.org/wiki/RSA
http://en.wikipedia.org/wiki/Public-key_cryptography
http://www.cs.princeton.edu/introcs/78crypto/RSA.java.html
http://pajhome.org.uk/crypt/rsa/implementation.html
www.cs.cityu.edu.hk/~cs4288/Java/RSA.doc
Readings for the most-interested.
(Extra credit if you can explain RSA to a cat)