Download BigInt - Andrew.cmu.edu

Document related concepts
no text concepts found
Transcript
Week 2
• Object-Oriented Programming
• Java’s BigInteger Class
• Java I/O and Client/Server
OOP, Java's BigInteger Class and I/O
1
Object-Oriented Programming and Java’s BigInteger Class
• Abstraction
The focus is on “what” not “how”.
• Encapsulation
Information hiding is used to promote
modularity and the use of abstractions.
• Polymorphism
We may want to treat an object not as an
instance of its specific type but as an instance
of its base type.
• Inheritance
OOP promotes code reuse via the “is-a”
relationship.
• Composition
OOP promotes code reuse via the “has-a”
relationship.
OOP, Java's BigInteger Class and I/O
2
Using Java’s BigInteger Class
import java.math.*;
public class TestBigInts {
public static void main(String args[] ) {
Abstraction
Encapsulation
BigInteger x = new BigInteger("1234567890123" +
"45678901234567890");
BigInteger y = new BigInteger("93939393929292" +
"9191919191919192");
BigInteger z = x.multiply(y);
System.out.println(z);
}
}
OOP, Java's BigInteger Class and I/O
3
The toString() method
public class BigInteger {
public String toString() {
A BigInteger “is a”
Object.
The println() method
calls toString().
// Returns the decimal String representation of this
// BigInteger.
// Overrides: toString() in class Object
}
Polymorphism
}
OOP, Java's BigInteger Class and I/O
4
Another Example
import java.math.*;
import java.util.*;
bitLength - bitLength of
the returned BigInteger.
public class TestBigInts {
public static void main(String args[] ) {
A Random object
assists with the
computation.
BigInteger m = new BigInteger(4,10, new Random(2456));
BigInteger n = new BigInteger(4,10, new Random(94));
certainty - a measure of
the uncertainty that the
caller is willing to
tolerate. Prob(prime) =
-10).
1-(2
OOP, Java's BigInteger Class and I/O
5
if(m.compareTo(n) < 0)
System.out.println(m + " < " + n );
else
System.out.println(m + " >= " + n );
}
}
Consider compareTo()
if(m.compareTo(n) < 0)
System.out.println(m + " < " + n );
else
System.out.println(m + " >= " + n );
public class BigInteger
extends Number
implements Comparable
Inheritance and Polymorphism
Comparable is an
interface that BigInteger
implements.
The BigInteger class
therefore has a method
called compareTo().
Any method
foo(Comparable x) can
be called with a
BigInteger.
OOP, Java's BigInteger Class and I/O
6
Another example
import java.math.*;
public class TestBigInts {
BigInteger extends
the abstract Number class.
public static void main(String args[] ) {
BigInteger m = new BigInteger("34");
foo(m);
No problem
}
public static void foo(Number n) {
long x = n.longValue();
x++;
System.out.println("x = " + x);
}
}
OOP, Java's BigInteger Class and I/O
7
Composition
import java.math.*;
class BigFraction {
private BigInteger numerator;
private BigInteger denominator;
A BigFraction
“has-a” BigInteger
numerator and a
BigInteger denominator.
public BigFraction(BigInteger num, BigInteger denom) {
numerator = num;
denominator = denom;
}
public BigFraction(String num, String denom) {
this(new BigInteger(num), new BigInteger(denom));
}
OOP, Java's BigInteger Class and I/O
8
Composition (cont.)
public String toString() {
return numerator + "/" + denominator;
}
}
public class TestBigInts {
public static void main(String args[]) {
BigFraction x = new BigFraction("1","2");
System.out.println(x);
}
}
OOP, Java's BigInteger Class and I/O
9
JAVA I/O AND
CLIENT/SERVER
OOP, Java's BigInteger Class and I/O
10
The Java IO System
• Different kinds of IO
– Files, the console, blocks of memory,
network connections
• Different kinds of operations
– Sequential, random- access, binary,
character, by lines, by words, etc.
OOP, Java's BigInteger Class and I/O
11
The Java IO Library Design
• Seems like a lot of classes
• Also seems at first like an odd design
– Not typically how you think of using classes
– Can require a lot of typing
• There is a plan
– A learning experience in class design
– The “Decorator” Design Pattern
OOP, Java's BigInteger Class and I/O
12
InputStream and OutputStream
• InputStream (Abstract class)
This abstract class is the superclass of all classes
representing an input stream of bytes.
• OutputStream (Abstract class)
This abstract class is the superclass of all classes
representing an output stream of bytes.
OOP, Java's BigInteger Class and I/O
13
Types of InputStream
ByteArrayInputStream
read memory block
StringBufferInputStream
buffer)
read from String (not
FileInputStream
read from file
PipedInputStream
thread
read from another
SequenceInputStream
streams
FilterInputStream
class.
reads from several
Decorators subclass this
OOP, Java's BigInteger Class and I/O
14
A FilterInputStream contains some other input stream, which
Two important FilterInputStream classes -Decorators
• DataInputStream (binary data)
• Full interface for reading primitive and built- in
types
• Construct with an InputStream
• When reading a float, four bytes are read
• BufferedInputStream
• Adds buffering to the stream (usually do this)
• Construct with an InputStream
OOP, Java's BigInteger Class and I/O
15
FileInputStream - Reading Data From a File
BufferedInputStream – Buffers input
DataInputStream – Reading binary data
readLine() -- deprecated
DataInputStream
BufferedInputStream
FileInputStream
String
File
Name
OOP, Java's BigInteger Class and I/O
16
// copy a binary or text file
import java.io.*;
public class CopyBytes {
public static void main( String args[]) throws IOException {
DataInputStream in =
new DataInputStream(
new BufferedInputStream(
new FileInputStream(args[0])));
DataOutputStream out =
new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(args[1])));
OOP, Java's BigInteger Class and I/O
17
byte byteIn;
try {
while(true) {
byteIn = in.readByte();
out.writeByte(byteIn);
}
}
catch(EOFException e) {
in.close();
out.close();
}
}
}
OOP, Java's BigInteger Class and I/O
18
Types of OutputStream
Writes to:
ByteArrayOutputStream
Block of memory
FileOutputStream
File
PipedOutputStream
thread)
“Pipe” (to another
FilterOutputStream
this
Decorators subclass
OOP, Java's BigInteger Class and I/O
class
19
Three important FilterOutputStream classes -Decorators
• DataOutputStream
– Full interface for writing primitive and built-in types;
complements
DataInputStream for portable reading & writing of data
DataOutputStream is normally for storage.
• PrintStream
– Allows primitive formatting for data display. Not as nice a
c’s printf(). Converts arguments to ASCII or EBCDIC. Use
PrintWriter when writing Unicode characters rather than
bytes.
OOP, Java's BigInteger Class and I/O
20
Writing Data To A File
PrintStream writes in the platform’s default
Encoding.
PrintStream
BufferedOutputStream
FileOutputStream
String
File
Name
OOP, Java's BigInteger Class and I/O
21
// Writing data to a file
import java.io.*;
public class OutPutDemo {
public static void main(String args[]) throws FileNotFoundException{
PrintStream out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("IODemo.out")));
out.println("Hello world...on a file");
out.close();
}
}
OOP, Java's BigInteger Class and I/O
22
DataOutPutStream is for binary output.
DataInputStream is for reading binary.
DataOutputStream
BufferedOutputStream
FileOutputStream
String
OOP, Java's BigInteger Class and I/O
23
// Writing data to a file In Binary not ASCII
import java.io.*;
public class OutPutDemo {
public static void main(String args[]) throws FileNotFoundException, IOException
{
DataOutputStream out = new DataOutputStream (
new BufferedOutputStream(
new FileOutputStream("Binary.out")));
out.writeDouble(3.34); // can’t view this!!
out.writeDouble(2.33);
out.close();
}
}
OOP, Java's BigInteger Class and I/O
24
PrintWriter replaces PrintStream.
Text output.
PrintWriter
BufferedWriter
FileWriter
String
OOP, Java's BigInteger Class and I/O
25
// Writing data to a file
import java.io.*;
public class OutPutDemo {
public static void main(String args[]) throws
FileNotFoundException, IOException {
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter("IODemo.out")));
out.println("Hello world...on a file");
out.close();
}
}
OOP, Java's BigInteger Class and I/O
26
Converting from an 8-bit InputStream to 16-bit Unicode
BufferedReader
InputStreamReader
Inputstream
Input stream
System.in
OOP, Java's BigInteger Class and I/O
27
import java.io.*;
public class InputDemo {
public static void main(String args[]) throws IOException
{
BufferedReader in =
new BufferedReader(
new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine();
System.out.println("Hello "+ name);
}
}
OOP, Java's BigInteger Class and I/O
28
Some Examples
// Demonstrate character I/O in Java
// Count the number of a's and b's
import java.io.*;
public class CharIO {
public static void main(String arg[]) throws IOException {
InputStreamReader is = new InputStreamReader(System.in);
System.out.println("Enter a line of text and I'll count the a's and b's");
OOP, Java's BigInteger Class and I/O
29
int aCount = 0;
int bCount = 0;
int i; // i should be an int so that we can detect a -1 from
// the read method. -1 is returned when read() sees
i = is.read(); // <ctrl><z> in DOS
while(i != '\n') { // DOS terminates each line with 13 10
char c = (char) i;
if(c == 'a') aCount++;
if(c == 'b') bCount++;
i = is.read();
}
System.out.println("a total = " + aCount + " b total = " + bCount);
}
}
OOP, Java's BigInteger Class and I/O
30
Some Examples
Count lines
// Demonstrate character I/O in Java
// Echo the input and count lines
import java.io.*;
public class CharIO2 {
public static void main(String arg[]) throws IOException {
InputStreamReader is = new InputStreamReader(System.in);
OOP, Java's BigInteger Class and I/O
31
System.out.println("I'll echo and count lines");
int lineCount = 0;
int i;
i = is.read(); // -1 = EOF = <ctrl><z> in DOS
while(i != -1) {
char c = (char) i;
if(c == '\n') lineCount++;
System.out.print(c);
i = is.read();
}
System.out.println("--------------------------");
System.out.println("Line count == " + lineCount);
}
}
OOP, Java's BigInteger Class and I/O
32
Some Examples
Using StringTokenizer
// Read a line of integers
// and display their sum
import java.io.*;
import java.util.*; // for StringTokenizer
public class LineOfInts {
public static void main(String arg[]) throws IOException
{
OOP, Java's BigInteger Class and I/O
33
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
StringTokenizer st;
System.out.println("Enter a line of integers");
String s = br.readLine();
// use comma, space, and tab for delimeters
t = new StringTokenizer(s, ", \t");
OOP, Java's BigInteger Class and I/O
34
int sum = 0;
while(st.hasMoreElements()) {
int val = Integer.parseInt(st.nextToken());
sum += val;
}
System.out.println("The sum is " + sum);
}
}
OOP, Java's BigInteger Class and I/O
35
Some Examples
Formatting a double
// display a number rounded to two decimal places
// at least one digit to the left of the decimal point
// # means a digit, 0 shows as absent
import java.io.*;
import java.text.*;
public class FormattedOutput {
static final double myDouble = 456.346;
public static void main(String arg[]) throws IOException
{
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(myDouble));
// displays 456.35
}
}
OOP, Java's BigInteger Class and I/O
36
Some Examples
// Java I/O
// Read a double and display its square root
import java.io.*;
public class DoubleIO {
public static void main(String arg[]) throws IOException
{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
OOP, Java's BigInteger Class and I/O
37
double x;
System.out.println("Enter a double and I'll compute the square root");
String inputString = br.readLine();
x = Double.parseDouble(inputString);
// displays NAN if x < 0
System.out.println("The square root of "+x+" is " + Math.sqrt(x));
}
}
OOP, Java's BigInteger Class and I/O
38
Object Serialization I/O
• Save or restore an object
• Works across networks (RMI arguments and
return values)
• Compensates for differences in operating
systems
• All relevant parts of an Object magically
stored and retrieved; even “web of
objects”
OOP, Java's BigInteger Class and I/O
39
Object serialization
• Class must implement Serializable
• Wrap a stream in a
ObjectOutputStream (for
writing)
or
ObjectInputStream (for reading)
• Use writeObject( ) and
readObject( )
OOP, Java's BigInteger Class and I/O
40
Some Examples
Writing BigIntegers
import java.math.*;
import java.io.*;
public class TestBigInts {
public static void main(String args[]) throws IOException {
BigInteger x = new BigInteger("1234567891011121314");
BigInteger y = new BigInteger("1234567890000000000");
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("bigints.dat"));
out.writeObject("Big Integer Storage");
out.writeObject(x);
out.writeObject(y);
}
}
OOP, Java's BigInteger Class and I/O
41
Some Examples
Reading BigIntegers
import java.math.*;
import java.io.*;
public class TestBigInts {
public static void main(String args[]) throws IOException,
ClassNotFoundException {
BigInteger x, y;
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("bigints.dat"));
String s = (String)in.readObject();
x = (BigInteger)in.readObject();
y = (BigInteger)in.readObject();
System.out.println(s + " " + x + " " + y);
}
OOP, Java's BigInteger Class and I/O
42
Some Examples List serialization
import java.util.*;
import java.io.*;
public class SaveAList implements Serializable {
public static void main(String args[])throws IOException,
ClassNotFoundException {
LinkedList stack = new LinkedList();
stack.addFirst("Little Cat A");
stack.addFirst("Little Cat B");
stack.addFirst("Little Cat C");
OOP, Java's BigInteger Class and I/O
43
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("CatStack.out"));
out.writeObject("The cat and the hat's hat cats");
out.writeObject(stack);
out.close();
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("CatStack.out"));
String s = (String) in.readObject();
LinkedList anotherStack = (LinkedList) in.readObject();
System.out.println(s + anotherStack);
}
}
OOP, Java's BigInteger Class and I/O
44
Output
C:\McCarthy\46935\io\Serialization>java SaveAList
The cat and the hat's hat cats[Little Cat C, Little Cat B, Little Cat A]
OOP, Java's BigInteger Class and I/O
45
I/O on the Net
• Historically error- prone, difficult, complex
• Threading is also very useful and relatively
easy here
• Excellent reference: “Java Network
Programming” by Elliotte Rusty Harold,
O’Reilly Books, 1997.
OOP, Java's BigInteger Class and I/O
46
Identifying a Machine
• Uniquely identify a machine from all the
others in
the world
• IP (Internet Protocol) address that can exist
in
two forms:
1) DNS (Domain Name Service) form:
hempel.heinz.cmu.edu
2) “Dotted quad” form: 128.2.240.92
• Represented internally by 32 bit number (4.3
billion possibilities. Oops!) (going to 128)
• static InetAddress.getByName(
) produces
OOP, Java's BigInteger Class and I/O
a
47
Servers & Clients
• Two machines must connect
• Server waits around for connection
• Client initiates connection
• Once the connection is made, server &
client look identical
• Both ends are turned into InputFile and
OutputFile objects, which can then be
converted to Reader and Writer
objects
OOP, Java's BigInteger Class and I/O
48
Testing w/ o a Network
You might not trust your code
• localhost : the “local loopback” IP address
for testing without a network InetAddress addr =
InetAddress.getByName(null);
• Equivalently:
InetAddress.getByName("localhost");
• Or using the reserved IP number for the
loopback:InetAddress.getByName("127.0.0.1");
• open two windows and talk
OOP, Java's BigInteger Class and I/O
49
Port: Unique “Place” in a Machine
• IP address isn’t enough to identify a unique
server
• Many servers can exist on one machine
Protocol
http server
ftp server
telnet
finger
Port
80
21
23
79
• A “server” is a program watching a port.
OOP, Java's BigInteger Class and I/O
50
Ports
• When you set up client and server, you must
specify IP address and port, so they can find
each
other
• Not a physical location, but a software
abstraction
to represent a service
• 1- 1024 are reserved (on Unix, root may access
these ports), higher numbered ports are available
OOP, Java's BigInteger Class and I/O
51
Sockets
• Software abstraction used to represent the “terminals” of a
connection between two machines
• Socket is the actual 2- way connector. Can initiate a
connection
with a server
• ServerSocket isn’t really a socket but more of a
“ServerConnector” that produces a Socket as the return
value of
accept( ) , which waits (blocks) for a connection.
• In the end, you get a Socket on each machine
OOP, Java's BigInteger Class and I/O
52
Just Like Files...
• Once you have a Socket , you call getInputStream( ) and
getOutputStream( ) to produce the corresponding
InputStream
and OutputStream objects
• You convert these to readers and writers, wrap them in a
BufferedReader or BufferedWriter and PrintWriter
• From then on, it’s like reading and writing any other IO
stream!
OOP, Java's BigInteger Class and I/O
53
Some Examples
Client/Server
// JabberServer. Java
// Very simple server that just
// echoes whatever the client sends.
// One client at a time. No threads yet!
import java. io.*;
import java. net.*;
public class JabberServer {
// Choose a port outside of the range 1- 1024:
static final int port = 8080;
public static void main( String[] args )
OOP, Java's BigInteger Class and I/O
54
try { boolean flush = true;
ServerSocket s = new ServerSocket(port);
System. out. println(" Server Started: " + s);
// Blocks until a connection occurs:
Socket socket = s.accept();
System. out. println(
"Connection accepted, socket: "+ socket);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())), flush);
OOP, Java's BigInteger Class and I/O
55
while (true) {
// till client says ‘END’
String str = in.readLine();
if (str.equals("END")) break;
System.out.println(" Echoing: " + str);
out.println(str);
}
System.out.println(" closing...");
socket.close();
} catch( Exception e) {
e.printStackTrace();
}
}
OOP, Java's BigInteger Class and I/O
56
// JabberClient. java
// Very simple client that just sends
// lines to the server and reads lines that the server sends.
import java. net.*;
import java. io.*;
public class JabberClient {
// Choose a port outside of the range 1- 1024:
static final int port = 8080;
public static void main( String args[]) {
try {
// Produce "Local Loopback" IP address
InetAddress addr =InetAddress.getByName(null);
System.out. println(" addr = " + addr);
Socket socket = new Socket(addr, port); // ‘remote’
server
System.out.println(" socket = " + socket);
OOP, Java's BigInteger Class and I/O
57
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Enable PrintWriter autoflush:
PrintWriter out = new PrintWriter( new
BufferedWriter(
new OutputStreamWriter(
socket. getOutputStream())),
flush);
OOP, Java's BigInteger Class and I/O
58
for( int i = 0; i < 10; i ++) {
out. println(" howdy " + i);
String str = in. readLine();
System. out. println( str);
}
out. println(" END");
} catch( Exception e) {
e. printStackTrace();
}
}
}
OOP, Java's BigInteger Class and I/O
59