corejava第7版

This commit is contained in:
deyou committed 2019-05-22 20:05:29 +08:00
1 parent e89542a214
commit fa8d1a5860
493 files changed
+105995

No files matched your search

@@ -0,0 +1,621 @@
package com.horstmann;
import java.io.*;
/**
A class for formatting numbers that follows <tt>printf</tt> conventions.
Also implements C-like <tt>atoi</tt> and <tt>atof</tt> functions
@version 1.21 2000-06-09
@author Cay Horstmann
1998-09-14: Fixed a number of bugs.
1.Formatting the most extreme negative number (-9223372036854775808L) printed with 2 leading minus signs.
2.Printing 0 with a %e or %g format did not work.
3.Printing numbers that were closer to 1 than the number of requested decimal places rounded down rather than up, e.g. formatting 1.999 with %.2f printed 1.00. (This one is pretty serious, of course.)
4.Printing with precision 0 (e.g %10.0f) didn't work.
5.Printing a string with a precision that exceeded the string length (e.g. print "Hello" with %20.10s) caused a StringIndexOutOfBounds error.
1998-10-21: Changed method names from print to printf
2000-06-09: Moved to package com.horstmann; no longer part of
Core Java
2000-06-09: Fixed a number of bugs.
1.Printing 100.0 with %e printed 10.0e1, not 1.0e2
2.Printing Inf and NaN didn't work.
2000-06-09: Coding guideline cleanup
*/
public class Format
{
/**
Formats the number following <tt>printf</tt> conventions.
Main limitation: Can only handle one format parameter at a time
Use multiple Format objects to format more than one number
@param s the format string following printf conventions
The string has a prefix, a format code and a suffix. The prefix and suffix
become part of the formatted output. The format code directs the
formatting of the (single) parameter to be formatted. The code has the
following structure
<ul>
<li> a % (required)
<li> a modifier (optional)
<dl>
<dt> + <dd> forces display of + for positive numbers
<dt> 0 <dd> show leading zeroes
<dt> - <dd> align left in the field
<dt> space <dd> prepend a space in front of positive numbers
<dt> # <dd> use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format.
</dl>
<li> an integer denoting field width (optional)
<li> a period followed by an integer denoting precision (optional)
<li> a format descriptor (required)
<dl>
<dt>f <dd> floating point number in fixed format
<dt>e, E <dd> floating point number in exponential notation (scientific format). The E format results in an uppercase E for the exponent (1.14130E+003), the e format in a lowercase e.
<dt>g, G <dd> floating point number in general format (fixed format for small numbers, exponential format for large numbers). Trailing zeroes are suppressed. The G format results in an uppercase E for the exponent (if any), the g format in a lowercase e.
<dt>d, i <dd> integer in decimal
<dt>x <dd> integer in hexadecimal
<dt>o <dd> integer in octal
<dt>s <dd> string
<dt>c <dd> character
</dl>
</ul>
@exception IllegalArgumentException if bad format
*/
public Format(String s)
{
width = 0;
precision = -1;
pre = "";
post = "";
leadingZeroes = false;
showPlus = false;
alternate = false;
showSpace = false;
leftAlign = false;
fmt = ' ';
int state = 0;
int length = s.length();
int parseState = 0;
// 0 = prefix, 1 = flags, 2 = width, 3 = precision,
// 4 = format, 5 = end
int i = 0;
while (parseState == 0)
{
if (i >= length) parseState = 5;
else if (s.charAt(i) == '%')
{
if (i < length - 1)
{
if (s.charAt(i + 1) == '%')
{
pre = pre + '%';
i++;
}
else
parseState = 1;
}
else throw new java.lang.IllegalArgumentException();
}
else
pre = pre + s.charAt(i);
i++;
}
while (parseState == 1)
{
if (i >= length) parseState = 5;
else if (s.charAt(i) == ' ') showSpace = true;
else if (s.charAt(i) == '-') leftAlign = true;
else if (s.charAt(i) == '+') showPlus = true;
else if (s.charAt(i) == '0') leadingZeroes = true;
else if (s.charAt(i) == '#') alternate = true;
else { parseState = 2; i--; }
i++;
}
while (parseState == 2)
{
if (i >= length) parseState = 5;
else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
{
width = width * 10 + s.charAt(i) - '0';
i++;
}
else if (s.charAt(i) == '.')
{
parseState = 3;
precision = 0;
i++;
}
else
parseState = 4;
}
while (parseState == 3)
{
if (i >= length) parseState = 5;
else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
{
precision = precision * 10 + s.charAt(i) - '0';
i++;
}
else
parseState = 4;
}
if (parseState == 4)
{
if (i >= length) parseState = 5;
else fmt = s.charAt(i);
i++;
}
if (i < length)
post = s.substring(i, length);
}
/**
prints a formatted number following printf conventions
@param fmt the format string
@param x the double to print
*/
public static void printf(String fmt, double x)
{
System.out.print(new Format(fmt).format(x));
}
/**
prints a formatted number following printf conventions
@param fmt the format string
@param x the int to print
*/
public static void printf(String fmt, int x)
{
System.out.print(new Format(fmt).format(x));
}
/**
prints a formatted number following printf conventions
@param fmt the format string
@param x the long to print
*/
public static void printf(String fmt, long x)
{
System.out.print(new Format(fmt).format(x));
}
/**
prints a formatted number following printf conventions
@param fmt the format string
@param x the character to print
*/
public static void printf(String fmt, char x)
{
System.out.print(new Format(fmt).format(x));
}
/**
prints a formatted number following printf conventions
@param fmt the format string
@param x a string to print
*/
public static void printf(String fmt, String x)
{
System.out.print(new Format(fmt).format(x));
}
/**
Converts a string of digits (decimal, octal or hex) to an integer
@param s a string
@return the numeric value of the prefix of s representing a base 10 integer
*/
public static int atoi(String s)
{
return (int)atol(s);
}
/**
Converts a string of digits (decimal, octal or hex) to a long integer
@param s a string
@return the numeric value of the prefix of s representing a base 10 integer
*/
public static long atol(String s)
{
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
if (i < s.length() && s.charAt(i) == '0')
{
if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X'))
return parseLong(s.substring(i + 2), 16);
else return parseLong(s, 8);
}
else return parseLong(s, 10);
}
private static long parseLong(String s, int base)
{
int i = 0;
int sign = 1;
long r = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
else if (i < s.length() && s.charAt(i) == '+') { i++; }
while (i < s.length())
{
char ch = s.charAt(i);
if ('0' <= ch && ch < '0' + base)
r = r * base + ch - '0';
else if ('A' <= ch && ch < 'A' + base - 10)
r = r * base + ch - 'A' + 10 ;
else if ('a' <= ch && ch < 'a' + base - 10)
r = r * base + ch - 'a' + 10 ;
else
return r * sign;
i++;
}
return r * sign;
}
/**
Converts a string of digits to a <tt>double</tt>
@param s a string
*/
public static double atof(String s)
{
int i = 0;
int sign = 1;
double r = 0; // integer part
double f = 0; // fractional part
double p = 1; // exponent of fractional part
int state = 0; // 0 = int part, 1 = frac part
while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
else if (i < s.length() && s.charAt(i) == '+') { i++; }
while (i < s.length())
{
char ch = s.charAt(i);
if ('0' <= ch && ch <= '9')
{
if (state == 0)
r = r * 10 + ch - '0';
else if (state == 1)
{
p = p / 10;
r = r + p * (ch - '0');
}
}
else if (ch == '.')
{
if (state == 0) state = 1;
else return sign * r;
}
else if (ch == 'e' || ch == 'E')
{
long e = (int)parseLong(s.substring(i + 1), 10);
return sign * r * Math.pow(10, e);
}
else return sign * r;
i++;
}
return sign * r;
}
/**
Formats a <tt>double</tt> into a string (like sprintf in C)
@param x the number to format
@return the formatted string
@exception IllegalArgumentException if bad argument
*/
public String format(double x)
{
String r;
if (precision < 0) precision = 6;
int s = 1;
if (x < 0) { x = -x; s = -1; }
if (Double.isNaN(x)) r = "NaN";
else if (x == Double.POSITIVE_INFINITY) r = "Inf";
else if (fmt == 'f')
r = fixedFormat(x);
else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G')
r = expFormat(x);
else throw new java.lang.IllegalArgumentException();
return pad(sign(s, r));
}
/**
Formats an integer into a string (like sprintf in C)
@param x the number to format
@return the formatted string
*/
public String format(int x)
{
long lx = x;
if (fmt == 'o' || fmt == 'x' || fmt == 'X')
lx &= 0xFFFFFFFFL;
return format(lx);
}
/**
Formats a long integer into a string (like sprintf in C)
@param x the number to format
@return the formatted string
*/
public String format(long x)
{
String r;
int s = 0;
if (fmt == 'd' || fmt == 'i')
{
if (x < 0)
{
r = ("" + x).substring(1);
s = -1;
}
else
{
r = "" + x;
s = 1;
}
}
else if (fmt == 'o')
r = convert(x, 3, 7, "01234567");
else if (fmt == 'x')
r = convert(x, 4, 15, "0123456789abcdef");
else if (fmt == 'X')
r = convert(x, 4, 15, "0123456789ABCDEF");
else throw new java.lang.IllegalArgumentException();
return pad(sign(s, r));
}
/**
Formats a character into a string (like sprintf in C)
@param x the value to format
@return the formatted string
*/
public String format(char c)
{
if (fmt != 'c')
throw new java.lang.IllegalArgumentException();
String r = "" + c;
return pad(r);
}
/**
Formats a string into a larger string (like sprintf in C)
@param x the value to format
@return the formatted string
*/
public String format(String s)
{
if (fmt != 's')
throw new java.lang.IllegalArgumentException();
if (precision >= 0 && precision < s.length())
s = s.substring(0, precision);
return pad(s);
}
/**
a test stub for the format class
*/
public static void main(String[] a)
{
double x = 1.23456789012;
double y = 123;
double z = 1.2345e30;
double w = 1.02;
double u = 1.234e-5;
int d = 0xCAFE;
Format.printf("x = |%f|\n", x);
Format.printf("u = |%20f|\n", u);
Format.printf("x = |% .5f|\n", x);
Format.printf("w = |%20.5f|\n", w);
Format.printf("x = |%020.5f|\n", x);
Format.printf("x = |%+20.5f|\n", x);
Format.printf("x = |%+020.5f|\n", x);
Format.printf("x = |% 020.5f|\n", x);
Format.printf("y = |%#+20.5f|\n", y);
Format.printf("y = |%-+20.5f|\n", y);
Format.printf("z = |%20.5f|\n", z);
Format.printf("x = |%e|\n", x);
Format.printf("u = |%20e|\n", u);
Format.printf("x = |% .5e|\n", x);
Format.printf("w = |%20.5e|\n", w);
Format.printf("x = |%020.5e|\n", x);
Format.printf("x = |%+20.5e|\n", x);
Format.printf("x = |%+020.5e|\n", x);
Format.printf("x = |% 020.5e|\n", x);
Format.printf("y = |%#+20.5e|\n", y);
Format.printf("y = |%-+20.5e|\n", y);
Format.printf("x = |%g|\n", x);
Format.printf("z = |%g|\n", z);
Format.printf("w = |%g|\n", w);
Format.printf("u = |%g|\n", u);
Format.printf("y = |%.2g|\n", y);
Format.printf("y = |%#.2g|\n", y);
Format.printf("d = |%d|\n", d);
Format.printf("d = |%20d|\n", d);
Format.printf("d = |%020d|\n", d);
Format.printf("d = |%+20d|\n", d);
Format.printf("d = |% 020d|\n", d);
Format.printf("d = |%-20d|\n", d);
Format.printf("d = |%20.8d|\n", d);
Format.printf("d = |%x|\n", d);
Format.printf("d = |%20X|\n", d);
Format.printf("d = |%#20x|\n", d);
Format.printf("d = |%020X|\n", d);
Format.printf("d = |%20.8x|\n", d);
Format.printf("d = |%o|\n", d);
Format.printf("d = |%020o|\n", d);
Format.printf("d = |%#20o|\n", d);
Format.printf("d = |%#020o|\n", d);
Format.printf("d = |%20.12o|\n", d);
Format.printf("s = |%-20s|\n", "Hello");
Format.printf("s = |%-20c|\n", '!');
// regression test to confirm fix of reported bugs
Format.printf("|%i|\n", Long.MIN_VALUE);
Format.printf("|%6.2e|\n", 0.0);
Format.printf("|%6.2g|\n", 0.0);
Format.printf("|%6.2f|\n", 9.99);
Format.printf("|%6.2f|\n", 9.999);
Format.printf("|%.2f|\n", 1.999);
Format.printf("|%6.0f|\n", 9.999);
Format.printf("|%20.10s|\n", "Hello");
d = -1;
Format.printf("-1 = |%X|\n", d);
Format.printf("100 = |%e|\n", 100.0); // 2000-06-09
Format.printf("1/0 = |%f|\n", 1.0 / 0.0);
Format.printf("-1/0 = |%e|\n", -1.0 / 0.0);
Format.printf("0/0 = |%g|\n", 0.0 / 0.0);
}
private static String repeat(char c, int n)
{
if (n <= 0) return "";
StringBuffer s = new StringBuffer(n);
for (int i = 0; i < n; i++) s.append(c);
return s.toString();
}
private static String convert(long x, int n, int m, String d)
{
if (x == 0) return "0";
String r = "";
while (x != 0)
{
r = d.charAt((int)(x & m)) + r;
x = x >>> n;
}
return r;
}
private String pad(String r)
{
String p = repeat(' ', width - r.length());
if (leftAlign) return pre + r + p + post;
else return pre + p + r + post;
}
private String sign(int s, String r)
{
String p = "";
if (s < 0) p = "-";
else if (s > 0)
{
if (showPlus) p = "+";
else if (showSpace) p = " ";
}
else
{
if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') p = "0";
else if (fmt == 'x' && alternate) p = "0x";
else if (fmt == 'X' && alternate) p = "0X";
}
int w = 0;
if (leadingZeroes)
w = width;
else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o')
&& precision > 0) w = precision;
return p + repeat('0', w - p.length() - r.length()) + r;
}
private String fixedFormat(double d)
{
boolean removeTrailing
= (fmt == 'G' || fmt == 'g') && !alternate;
// remove trailing zeroes and decimal point
if (d > 0x7FFFFFFFFFFFFFFFL) return expFormat(d);
if (precision == 0)
return (long)(d + 0.5) + (removeTrailing ? "" : ".");
long whole = (long)d;
double fr = d - whole; // fractional part
if (fr >= 1 || fr < 0) return expFormat(d);
double factor = 1;
String leadingZeroes = "";
for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++)
{
factor *= 10;
leadingZeroes = leadingZeroes + "0";
}
long l = (long) (factor * fr + 0.5);
if (l >= factor) { l = 0; whole++; } // CSH 10-25-97
String z = leadingZeroes + l;
z = "." + z.substring(z.length() - precision, z.length());
if (removeTrailing)
{
int t = z.length() - 1;
while (t >= 0 && z.charAt(t) == '0') t--;
if (t >= 0 && z.charAt(t) == '.') t--;
z = z.substring(0, t + 1);
}
return whole + z;
}
private String expFormat(double d)
{
String f = "";
int e = 0;
double dd = d;
double factor = 1;
if (d != 0)
{
while (dd >= 10) { e++; factor /= 10; dd = dd / 10; } // 2000-06-09
while (dd < 1) { e--; factor *= 10; dd = dd * 10; }
}
if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision)
return fixedFormat(d);
d = d * factor;
f = f + fixedFormat(d);
if (fmt == 'e' || fmt == 'g')
f = f + "e";
else
f = f + "E";
String p = "000";
if (e >= 0)
{
f = f + "+";
p = p + e;
}
else
{
f = f + "-";
p = p + (-e);
}
return f + p.substring(p.length() - 3, p.length());
}
private int width;
private int precision;
private String pre;
private String post;
private boolean leadingZeroes;
private boolean showPlus;
private boolean alternate;
private boolean showSpace;
private boolean leftAlign;
private char fmt; // one of cdeEfgGiosxXos
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,62 @@
/**
@version 1.31 2004-05-07
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
public class AppletFrame extends JFrame
implements AppletStub, AppletContext
{
public AppletFrame(Applet anApplet)
{
applet = anApplet;
add(applet);
applet.setStub(this);
}
public void setVisible(boolean b)
{
if (b)
{
applet.init();
super.setVisible(true);
applet.start();
}
else
{
applet.stop();
super.setVisible(false);
applet.destroy();
}
}
// AppletStub methods
public boolean isActive() { return true; }
public URL getDocumentBase() { return null; }
public URL getCodeBase() { return null; }
public String getParameter(String name) { return ""; }
public AppletContext getAppletContext() { return this; }
public void appletResize(int width, int height) {}
// AppletContext methods
public AudioClip getAudioClip(URL url) { return null; }
public Image getImage(URL url) { return null; }
public Applet getApplet(String name) { return null; }
public Enumeration getApplets() { return null; }
public void showDocument(URL url) {}
public void showDocument(URL url, String target) {}
public void showStatus(String status) {}
public void setStream(String key, InputStream stream) {}
public InputStream getStream(String key) { return null; }
public Iterator getStreamKeys() { return null; }
private Applet applet;
}
@@ -0,0 +1,147 @@
/**
@version 1.31 2004-05-07
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalculatorApplet extends JApplet
{
public void init()
{
add(new CalculatorPanel());
}
}
/**
A panel with calculator buttons and a result display.
*/
class CalculatorPanel extends JPanel
{
public CalculatorPanel()
{
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;
// add the display
display = new JLabel("0");
add(display, BorderLayout.NORTH);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
// add the buttons in a 4 x 4 grid
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);
addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);
add(panel, BorderLayout.CENTER);
}
/**
Adds a button to the center panel.
@param label the button label
@param listener the button listener
*/
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
/**
This action inserts the button action string to the
end of the display text.
*/
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input = event.getActionCommand();
if (start)
{
display.setText("");
start = false;
}
display.setText(display.getText() + input);
}
}
/**
This action executes the command that the button
action string denotes.
*/
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (start)
{
if (command.equals("-"))
{
display.setText(command);
start = false;
}
else
lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start = true;
}
}
}
/**
Carries out the pending calculation.
@param x the value to be accumulated with the prior result.
*/
public void calculate(double x)
{
if (lastCommand.equals("+")) result += x;
else if (lastCommand.equals("-")) result -= x;
else if (lastCommand.equals("*")) result *= x;
else if (lastCommand.equals("/")) result /= x;
else if (lastCommand.equals("=")) result = x;
display.setText("" + result);
}
private JLabel display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}
@@ -0,0 +1,3 @@
<applet code="CalculatorAppletApplication.class"
width="180" height="180">
</applet>
@@ -0,0 +1,32 @@
/**
@version 1.31 2004-05-07
@author Cay Horstmann
*/
/*
The applet viewer reads the tags below if you call it with
appletviewer CalculatorAppletApplication.java (!)
No separate HTML file is required.
<applet code="CalculatorAppletApplication.class" width="200" height="200">
</applet>
*/
import javax.swing.*;
public class CalculatorAppletApplication
extends CalculatorApplet
// It's an applet. It's an application. It's BOTH!
{
public static void main(String[] args)
{
AppletFrame frame = new AppletFrame(new CalculatorApplet());
frame.setTitle("CalculatorAppletApplication");
frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static final int DEFAULT_WIDTH = 200;
public static final int DEFAULT_HEIGHT = 200;
}
@@ -0,0 +1,14 @@
<html>
<head>
<title>Bookmark Applet</title>
</head>
<frameset cols="320,*">
<frame name="left" src="Left.html"
marginheight="2" marginwidth="2"
scrolling="no" noresize="noresize"/>
<frame name="right" src="Right.html"
marginheight="2" marginwidth="2"
scrolling="yes" noresize="noresize"/>
</frameset>
</html>
@@ -0,0 +1,58 @@
/**
@version 1.22 2004-05-07
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
public class Bookmark extends JApplet
{
public void init()
{
Box box = Box.createVerticalBox();
ButtonGroup group = new ButtonGroup();
int i = 1;
String urlString;
// read all link.n parameters
while ((urlString = getParameter("link." + i)) != null)
{
try
{
final URL url = new URL(urlString);
// make a radio button for each link
JRadioButton button = new JRadioButton(urlString);
box.add(button);
group.add(button);
// selecting the radio button shows the URL in the "right" frame
button.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
AppletContext context = getAppletContext();
context.showDocument(url, "right");
}
});
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
i++;
}
add(box);
}
}
@@ -0,0 +1,22 @@
<html>
<head><title>A Bookmark Applet</title></head>
<body>
<p>
Click on one of the radio buttons.
The corresponding web page
will be displayed in the frame on the right.
</p>
<applet code="Bookmark.class" width="290" height="300">
<param name="link.1" value="http://java.sun.com"/>
<param name="link.2" value="http://java.net"/>
<param name="link.3" value="http://linuxtoday.com"/>
<param name="link.4" value="http://www.horstmann.com"/>
<param name="link.5" value="http://www.phptr.com"/>
<param name="link.6" value="http://usps.com"/>
<param name="link.7" value="http://www.cafeaulait.org"/>
</applet>
</body>
</html>
@@ -0,0 +1,7 @@
<html>
<head><title>Web pages will be displayed here.</title></head>
<body>
<p>Click on one of the radio buttons to the left.
The corresponding web page will be displayed here.</p>
</body>
</html>
@@ -0,0 +1,8 @@
<html>
<head><title>A Calculator</title></head>
<body>
<p>Here is a calculator, just in case you can't find yours.</p>
<applet code="CalculatorApplet.class" width="180" height="180">
</applet>
</body>
</html>
@@ -0,0 +1,20 @@
/**
@version 1.31 2004-05-07
@author Cay Horstmann
*/
import java.awt.*;
import javax.swing.*;
public class CalculatorApplet extends JApplet
{
public void init()
{
CalculatorPanel panel = new CalculatorPanel();
add(panel);
}
}
@@ -0,0 +1,137 @@
/**
@version 1.31 2004-05-07
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
A panel with calculator buttons and a result display.
*/
class CalculatorPanel extends JPanel
{
public CalculatorPanel()
{
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;
// add the display
display = new JLabel("0");
add(display, BorderLayout.NORTH);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
// add the buttons in a 4 x 4 grid
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);
addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);
add(panel, BorderLayout.CENTER);
}
/**
Adds a button to the center panel.
@param label the button label
@param listener the button listener
*/
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
/**
This action inserts the button action string to the
end of the display text.
*/
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input = event.getActionCommand();
if (start)
{
display.setText("");
start = false;
}
display.setText(display.getText() + input);
}
}
/**
This action executes the command that the button
action string denotes.
*/
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (start)
{
if (command.equals("-"))
{
display.setText(command);
start = false;
}
else
lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start = true;
}
}
}
/**
Carries out the pending calculation.
@param x the value to be accumulated with the prior result.
*/
public void calculate(double x)
{
if (lastCommand.equals("+")) result += x;
else if (lastCommand.equals("-")) result -= x;
else if (lastCommand.equals("*")) result *= x;
else if (lastCommand.equals("/")) result /= x;
else if (lastCommand.equals("=")) result = x;
display.setText("" + result);
}
private JLabel display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}
@@ -0,0 +1,22 @@
<applet code="Chart.class" width=400 height=300>
<param name="title" value="Diameters of the Planets"/>
<param name="values" value="9"/>
<param name="name.1" value="Mercury"/>
<param name="name.2" value="Venus"/>
<param name="name.3" value="Earth"/>
<param name="name.4" value="Mars"/>
<param name="name.5" value="Jupiter"/>
<param name="name.6" value="Saturn"/>
<param name="name.7" value="Uranus"/>
<param name="name.8" value="Neptune"/>
<param name="name.9" value="Pluto"/>
<param name="value.1" value="3100"/>
<param name="value.2" value="7500"/>
<param name="value.3" value="8000"/>
<param name="value.4" value="4200"/>
<param name="value.5" value="88000"/>
<param name="value.6" value="71000"/>
<param name="value.7" value="32000"/>
<param name="value.8" value="30600"/>
<param name="value.9" value="1430"/>
</applet>
+130
View File
@@ -0,0 +1,130 @@
/**
@version 1.32 2004-05-07
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
public class Chart extends JApplet
{
public void init()
{
String v = getParameter("values");
if (v == null) return;
int n = Integer.parseInt(v);
double[] values = new double[n];
String[] names = new String[n];
for (int i = 0; i < n; i++)
{
values[i] = Double.parseDouble(getParameter("value." + (i + 1)));
names[i] = getParameter("name." + (i + 1));
}
add(new ChartPanel(values, names, getParameter("title")));
}
}
/**
A panel that draws a bar chart.
*/
class ChartPanel extends JPanel
{
/**
Constructs a ChartPanel.
@param v the array of values for the chart
@param n the array of names for the values
@param t the title of the chart
*/
public ChartPanel(double[] v, String[] n, String t)
{
values = v;
names = n;
title = t;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// compute the minimum and maximum values
if (values == null) return;
double minValue = 0;
double maxValue = 0;
for (double v : values)
{
if (minValue > v) minValue = v;
if (maxValue < v) maxValue = v;
}
if (maxValue == minValue) return;
int panelWidth = getWidth();
int panelHeight = getHeight();
Font titleFont = new Font("SansSerif", Font.BOLD, 20);
Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
// compute the extent of the title
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D titleBounds = titleFont.getStringBounds(title, context);
double titleWidth = titleBounds.getWidth();
double top = titleBounds.getHeight();
// draw the title
double y = -titleBounds.getY(); // ascent
double x = (panelWidth - titleWidth) / 2;
g2.setFont(titleFont);
g2.drawString(title, (float) x, (float) y);
// compute the extent of the bar labels
LineMetrics labelMetrics = labelFont.getLineMetrics("", context);
double bottom = labelMetrics.getHeight();
y = panelHeight - labelMetrics.getDescent();
g2.setFont(labelFont);
// get the scale factor and width for the bars
double scale = (panelHeight - top - bottom) / (maxValue - minValue);
int barWidth = panelWidth / values.length;
// draw the bars
for (int i = 0; i < values.length; i++)
{
// get the coordinates of the bar rectangle
double x1 = i * barWidth + 1;
double y1 = top;
double height = values[i] * scale;
if (values[i] >= 0)
y1 += (maxValue - values[i]) * scale;
else
{
y1 += maxValue * scale;
height = -height;
}
// fill the bar and draw the bar outline
Rectangle2D rect = new Rectangle2D.Double(x1, y1, barWidth - 2, height);
g2.setPaint(Color.RED);
g2.fill(rect);
g2.setPaint(Color.BLACK);
g2.draw(rect);
// draw the centered label below the bar
Rectangle2D labelBounds = labelFont.getStringBounds(names[i], context);
double labelWidth = labelBounds.getWidth();
x = x1 + (barWidth - labelWidth) / 2;
g2.drawString(names[i], (float) x, (float) y);
}
}
private double[] values;
private String[] names;
private String title;
}
@@ -0,0 +1,76 @@
/**
@version 1.22 2004-05-08
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
/**
This program demonstrates how to customize a "Hello, World"
program with a properties file.
*/
public class CustomWorld
{
public static void main(String[] args)
{
CustomWorldFrame frame = new CustomWorldFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
This frame displays a message. The frame size, message text,
font, and color are set in a properties file.
*/
class CustomWorldFrame extends JFrame
{
public CustomWorldFrame()
{
Properties defaultSettings = new Properties();
defaultSettings.put("font", "Monospaced");
defaultSettings.put("width", "300");
defaultSettings.put("height", "200");
defaultSettings.put("message", "Hello, World");
defaultSettings.put("color.red", "0 50 50");
defaultSettings.put("color.green", "50");
defaultSettings.put("color.blue", "50");
defaultSettings.put("ptsize", "12");
Properties settings = new Properties(defaultSettings);
try
{
FileInputStream in = new FileInputStream("CustomWorld.properties");
settings.load(in);
}
catch (IOException e)
{
e.printStackTrace();
}
int red = Integer.parseInt(settings.getProperty("color.red"));
int green = Integer.parseInt(settings.getProperty("color.green"));
int blue = Integer.parseInt(settings.getProperty("color.blue"));
Color foreground = new Color(red, green, blue);
String name = settings.getProperty("font");
int ptsize = Integer.parseInt(settings.getProperty("ptsize"));
Font f = new Font(name, Font.BOLD, ptsize);
int hsize = Integer.parseInt(settings.getProperty("width"));
int vsize = Integer.parseInt(settings.getProperty("height"));
setSize(hsize, vsize);
setTitle(settings.getProperty("message"));
JLabel label = new JLabel(settings.getProperty("message"), SwingConstants.CENTER);
label.setFont(f);
label.setForeground(foreground);
add(label);
}
}
@@ -0,0 +1,11 @@
#CustomWorld Properties
#Sat May 08 08:27:34 PDT 2004
font=Serif
width=400
height=200
message=Hello, Custom World!
color.red=0
color.green=50
color.blue=100
ptsize=36
@@ -0,0 +1,3 @@
<applet code="NotHelloWorldApplet.class"
width="300" height="100">
</applet>
@@ -0,0 +1,21 @@
/**
@version 1.21 2004-05-07
@author Cay Horstmann
*/
/*
The following HTML tags are required to display this applet in a browser:
<applet code="NotHelloWorldApplet.class" width="300" height="100">
</applet>
*/
import javax.swing.*;
public class NotHelloWorldApplet extends JApplet
{
public void init()
{
JLabel label = new JLabel("Not a Hello, World applet", SwingConstants.CENTER);
add(label);
}
}
@@ -0,0 +1,137 @@
/**
@version 1.31 2004-05-07
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
A panel with calculator buttons and a result display.
*/
class CalculatorPanel extends JPanel
{
public CalculatorPanel()
{
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;
// add the display
display = new JLabel("0");
add(display, BorderLayout.NORTH);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
// add the buttons in a 4 x 4 grid
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);
addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);
add(panel, BorderLayout.CENTER);
}
/**
Adds a button to the center panel.
@param label the button label
@param listener the button listener
*/
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
/**
This action inserts the button action string to the
end of the display text.
*/
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input = event.getActionCommand();
if (start)
{
display.setText("");
start = false;
}
display.setText(display.getText() + input);
}
}
/**
This action executes the command that the button
action string denotes.
*/
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (start)
{
if (command.equals("-"))
{
display.setText(command);
start = false;
}
else
lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start = true;
}
}
}
/**
Carries out the pending calculation.
@param x the value to be accumulated with the prior result.
*/
public void calculate(double x)
{
if (lastCommand.equals("+")) result += x;
else if (lastCommand.equals("-")) result -= x;
else if (lastCommand.equals("*")) result *= x;
else if (lastCommand.equals("/")) result /= x;
else if (lastCommand.equals("=")) result = x;
display.setText("" + result);
}
private JLabel display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}
@@ -0,0 +1,9 @@
<html>
<title>A Calculator</title>
<body>
Click this button to pop up a calculator.
<applet align="middle" code="PopupCalculatorApplet.class"
width="100" height="20">
</applet>
</body>
</html>
@@ -0,0 +1,38 @@
/**
@version 1.31 2004-05-07
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopupCalculatorApplet extends JApplet
{
public void init()
{
// create a frame with a calculator panel
final JFrame frame = new JFrame();
frame.setTitle("Calculator");
frame.setSize(200, 200);
frame.add(new CalculatorPanel());
// add a button that pops up or hides the calculator
JButton calcButton = new JButton("Calculator");
add(calcButton);
calcButton.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
frame.setVisible(!frame.isVisible());
}
});
}
}
@@ -0,0 +1,137 @@
/**
@version 1.01 2004-05-08
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.*;
import java.util.prefs.*;
import javax.swing.*;
import javax.swing.event.*;
/**
A program to test preference settings. The program
remembers the frame position and size.
*/
public class PreferencesTest
{
public static void main(String[] args)
{
PreferencesFrame frame = new PreferencesFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame that restores position and size from user
preferences and updates the preferences upon exit.
*/
class PreferencesFrame extends JFrame
{
public PreferencesFrame()
{
setTitle("PreferencesTest");
// get position, size from preferences
Preferences root = Preferences.userRoot();
final Preferences node = root.node("/com/horstmann/corejava");
int left = node.getInt("left", 0);
int top = node.getInt("top", 0);
int width = node.getInt("width", DEFAULT_WIDTH);
int height = node.getInt("height", DEFAULT_HEIGHT);
setBounds(left, top, width, height);
// set up file chooser that shows XML files
final JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
// accept all files ending with .xml
chooser.setFileFilter(new
javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();
}
public String getDescription()
{
return "XML files";
}
});
// set up menus
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem exportItem = new JMenuItem("Export preferences");
menu.add(exportItem);
exportItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)
{
try
{
OutputStream out = new FileOutputStream(chooser.getSelectedFile());
node.exportSubtree(out);
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
JMenuItem importItem = new JMenuItem("Import preferences");
menu.add(importItem);
importItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)
{
try
{
InputStream in = new FileInputStream(chooser.getSelectedFile());
node.importPreferences(in);
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
node.putInt("left", getX());
node.putInt("top", getY());
node.putInt("width", getWidth());
node.putInt("height", getHeight());
System.exit(0);
}
});
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
@@ -0,0 +1,74 @@
/**
@version 1.31 2004-05-07
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
public class ResourceTest
{
public static void main(String[] args)
{
ResourceTestFrame frame = new ResourceTestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame with a panel that has components demonstrating
resource access from a JAR file.
*/
class ResourceTestFrame extends JFrame
{
public ResourceTestFrame()
{
setTitle("ResourceTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
add(new AboutPanel());
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 300;
}
/**
A panel with a text area and an "About" button. Pressing
the button fills the text area with text from a resource.
*/
class AboutPanel extends JPanel
{
public AboutPanel()
{
setLayout(new BorderLayout());
// add text area
textArea = new JTextArea();
add(new JScrollPane(textArea), BorderLayout.CENTER);
// add About button
URL aboutURL = AboutPanel.class.getResource("about.gif");
JButton aboutButton = new JButton("About", new ImageIcon(aboutURL));
aboutButton.addActionListener(new AboutAction());
add(aboutButton, BorderLayout.SOUTH);
}
private JTextArea textArea;
private class AboutAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
InputStream stream = AboutPanel.class.getResourceAsStream("about.txt");
Scanner in = new Scanner(stream);
while (in.hasNext())
textArea.append(in.nextLine() + "\n");
}
}
}
@@ -0,0 +1 @@
Main-Class: ResourceTest
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

@@ -0,0 +1,5 @@
Core Java 2: Fundamentals
7th Edition
Cay Horstmann and Gary Cornell
Copyright (C) 2004
Sun Microsystems Press
@@ -0,0 +1,27 @@
/**
@version 1.10 2002-07-06
@author Cay Horstmann
*/
import java.applet.*;
import java.io.*;
import java.util.*;
/**
This program prints out all system properties.
*/
public class SystemInfo
{
public static void main(String args[])
{
try
{
Properties sysprops = System.getProperties();
sysprops.store(System.out, "System Properties");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
@@ -0,0 +1,344 @@
/**
@version 1.01 2004-05-08
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.jnlp.*;
/**
A calculator with a calculation history that can be
deployed as a Java Web Start application.
*/
public class WebStartCalculator
{
public static void main(String[] args)
{
CalculatorFrame frame = new CalculatorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame with a calculator panel and a menu to load and
save the calculator history.
*/
class CalculatorFrame extends JFrame
{
public CalculatorFrame()
{
setTitle();
panel = new CalculatorPanel();
add(panel);
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = fileMenu.add("Open");
openItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
open();
}
});
JMenuItem saveItem = fileMenu.add("Save");
saveItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
save();
}
});
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
setJMenuBar(menuBar);
pack();
}
/**
Gets the title from the persistent store or
asks the user for the title if there is no prior entry.
*/
public void setTitle()
{
try
{
String title = null;
BasicService basic = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
URL codeBase = basic.getCodeBase();
PersistenceService service
= (PersistenceService) ServiceManager.lookup("javax.jnlp.PersistenceService");
URL key = new URL(codeBase, "title");
try
{
FileContents contents = service.get(key);
InputStream in = contents.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
title = reader.readLine();
}
catch (FileNotFoundException e)
{
title = JOptionPane.showInputDialog("Please supply a frame title:");
if (title == null) return;
service.create(key, 100);
FileContents contents = service.get(key);
OutputStream out = contents.getOutputStream(true);
PrintStream printOut = new PrintStream(out);
printOut.print(title);
}
setTitle(title);
}
catch (UnavailableServiceException e)
{
JOptionPane.showMessageDialog(this, e);
}
catch (MalformedURLException e)
{
JOptionPane.showMessageDialog(this, e);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, e);
}
}
/**
Opens a history file and updates the display.
*/
public void open()
{
try
{
FileOpenService service
= (FileOpenService) ServiceManager.lookup("javax.jnlp.FileOpenService");
FileContents contents = service.openFileDialog(".", new String[] { "txt" });
JOptionPane.showMessageDialog(this, contents.getName());
if (contents != null)
{
InputStream in = contents.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null)
{
panel.append(line);
panel.append("\n");
}
}
}
catch (UnavailableServiceException e)
{
JOptionPane.showMessageDialog(this, e);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, e);
}
}
/**
Saves the calculator history to a file.
*/
public void save()
{
try
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream printOut = new PrintStream(out);
printOut.print(panel.getText());
InputStream data = new ByteArrayInputStream(out.toByteArray());
FileSaveService service
= (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService");
service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt");
}
catch (UnavailableServiceException e)
{
JOptionPane.showMessageDialog(this, e);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, e);
}
}
private CalculatorPanel panel;
}
/**
A panel with calculator buttons and a result display.
*/
class CalculatorPanel extends JPanel
{
/**
Lays out the panel.
*/
public CalculatorPanel()
{
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;
// add the display
display = new JTextArea(10, 20);
add(new JScrollPane(display), BorderLayout.NORTH);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
// add the buttons in a 4 x 4 grid
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);
addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);
add(panel, BorderLayout.CENTER);
}
/**
Gets the history text.
@return the calculator history
*/
public String getText()
{
return display.getText();
}
/**
Appends a string to the history text.
@param s the string to append
*/
public void append(String s)
{
display.append(s);
}
/**
Adds a button to the center panel.
@param label the button label
@param listener the button listener
*/
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
/**
This action inserts the button action string to the
end of the display text.
*/
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input = event.getActionCommand();
start = false;
display.append(input);
}
}
/**
This action executes the command that the button
action string denotes.
*/
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (start)
{
if (command.equals("-"))
{
display.append(command);
start = false;
}
else
lastCommand = command;
}
else
{
try
{
int lines = display.getLineCount();
int lineStart = display.getLineStartOffset(lines - 1);
int lineEnd = display.getLineEndOffset(lines - 1);
String value = display.getText(lineStart, lineEnd - lineStart);
display.append(" ");
display.append(command);
calculate(Double.parseDouble(value));
if (command.equals("="))
display.append("\n" + result);
lastCommand = command;
display.append("\n");
start = true;
}
catch (BadLocationException e)
{
e.printStackTrace();
}
}
}
}
/**
Carries out the pending calculation.
@param x the value to be accumulated with the prior result.
*/
public void calculate(double x)
{
if (lastCommand.equals("+")) result += x;
else if (lastCommand.equals("-")) result -= x;
else if (lastCommand.equals("*")) result *= x;
else if (lastCommand.equals("/")) result /= x;
else if (lastCommand.equals("=")) result = x;
}
private JTextArea display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8080/calculator/" href="WebStartCalculator.jnlp">
<information>
<title>Calculator Demo Application</title>
<vendor>Cay S. Horstmann</vendor>
<description>Web Start Calculator</description>
<offline-allowed/>
</information>
<resources>
<j2se version="1.5+"/>
<jar href="WebStartCalculator.jar"/>
</resources>
<application-desc/>
</jnlp>
@@ -0,0 +1 @@
Main-Class: WebStartCalculator
@@ -0,0 +1,24 @@
/**
@version 1.22 2004-05-11
@author Cay Horstmann
*/
import java.awt.*;
import javax.swing.*;
public class BuggyButtonFrame extends JFrame
{
public BuggyButtonFrame()
{
setTitle("BuggyButtonTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add panel to frame
BuggyButtonPanel panel = new BuggyButtonPanel();
add(panel);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
@@ -0,0 +1,43 @@
/**
@version 1.21 2002-07-06
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class BuggyButtonPanel extends JPanel
{
public BuggyButtonPanel()
{
ActionListener listener = new ButtonListener();
JButton yellowButton = new JButton("Yellow");
add(yellowButton);
yellowButton.addActionListener(listener);
JButton blueButton = new JButton("Blue");
add(blueButton);
blueButton.addActionListener(listener);
JButton redButton = new JButton("Red");
add(redButton);
redButton.addActionListener(listener);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String arg = event.getActionCommand();
if (arg.equals("yellow"))
setBackground(Color.yellow);
else if (arg.equals("blue"))
setBackground(Color.blue);
else if (arg.equals("red"))
setBackground(Color.red);
}
}
}
@@ -0,0 +1,17 @@
/**
@version 1.21 2004-05-11
@author Cay Horstmann
*/
import javax.swing.*;
public class BuggyButtonTest
{
public static void main(String[] args)
{
BuggyButtonFrame frame = new BuggyButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
@@ -0,0 +1,50 @@
/**
@version 1.01 2004-05-10
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
/**
A window that displays the bytes sent to System.out
and System.err
*/
public class ConsoleWindow
{
public static void init()
{
JFrame frame = new JFrame();
frame.setTitle("ConsoleWindow");
final JTextArea output = new JTextArea();
output.setEditable(false);
frame.add(new JScrollPane(output));
frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
frame.setLocation(DEFAULT_LEFT, DEFAULT_TOP);
frame.setFocusableWindowState(false);
frame.setVisible(true);
// define a PrintStream that sends its bytes to the
// output text area
PrintStream consoleStream = new PrintStream(new
OutputStream()
{
public void write(int b) {} // never called
public void write(byte[] b, int off, int len)
{
output.append(new String(b, off, len));
}
});
// set both System.out and System.err to that stream
System.setOut(consoleStream);
System.setErr(consoleStream);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
public static final int DEFAULT_LEFT = 200;
public static final int DEFAULT_TOP = 200;
}
@@ -0,0 +1,97 @@
/**
@version 1.22 2004-05-11
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ConsoleWindowTest
{
public static void main(String[] args)
{
// this is the button test program from chapter 8
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// initialize the console window--System.out will show here
ConsoleWindow.init();
}
}
/**
A frame with a button panel
This code is identical to ButtonTest in chapter 8, except
for the logging in the actionPerformed method of the
ColorAction class
*/
class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("ButtonTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add panel to frame
ButtonPanel panel = new ButtonPanel();
add(panel);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
/**
A panel with three buttons
*/
class ButtonPanel extends JPanel
{
public ButtonPanel()
{
// create buttons
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");
// add buttons to panel
add(yellowButton);
add(blueButton);
add(redButton);
// create button actions
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED);
// associate actions with buttons
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
/**
An action listener that sets the panel's background color.
*/
private class ColorAction implements ActionListener
{
public ColorAction(Color c)
{
backgroundColor = c;
}
public void actionPerformed(ActionEvent event)
{
System.out.println(event); // shows in console window
setBackground(backgroundColor);
}
private Color backgroundColor;
}
}
@@ -0,0 +1,78 @@
/**
@version 1.31 2004-05-10
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.lang.reflect.*;
public class EventTracer
{
public EventTracer()
{
// the handler for all event proxies
handler = new
InvocationHandler()
{
public Object invoke(Object proxy, Method method, Object[] args)
{
System.out.println(method + ":" + args[0]);
return null;
}
};
}
/**
Adds event tracers for all events to which this component
and its children can listen
@param c a component
*/
public void add(Component c)
{
try
{
// get all events to which this component can listen
BeanInfo info = Introspector.getBeanInfo(c.getClass());
EventSetDescriptor[] eventSets = info.getEventSetDescriptors();
for (EventSetDescriptor eventSet : eventSets)
addListener(c, eventSet);
}
catch (IntrospectionException e) {}
// ok not to add listeners if exception is thrown
if (c instanceof Container)
{
// get all children and call add recursively
for (Component comp : ((Container) c).getComponents())
add(comp);
}
}
/**
Add a listener to the given event set
@param c a component
@param eventSet a descriptor of a listener interface
*/
public void addListener(Component c, EventSetDescriptor eventSet)
{
// make proxy object for this listener type and route all calls to the handler
Object proxy = Proxy.newProxyInstance(null,
new Class[] { eventSet.getListenerType() }, handler);
// add the proxy as a listener to the component
Method addListenerMethod = eventSet.getAddListenerMethod();
try
{
addListenerMethod.invoke(c, proxy);
}
catch(InvocationTargetException e) {}
catch(IllegalAccessException e) {}
// ok not to add listener if exception is thrown
}
private InvocationHandler handler;
}
@@ -0,0 +1,38 @@
/**
@version 1.12 2004-05-10
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventTracerTest
{
public static void main(String[] args)
{
JFrame frame = new EventTracerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class EventTracerFrame extends JFrame
{
public EventTracerFrame()
{
setTitle("EventTracerTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add a slider and a button
add(new JSlider(), BorderLayout.NORTH);
add(new JButton("Test"), BorderLayout.SOUTH);
// trap all events of components inside the frame
EventTracer tracer = new EventTracer();
tracer.add(this);
}
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 400;
}
@@ -0,0 +1,181 @@
/**
@version 1.32 2004-05-10
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class ExceptTest
{
public static void main(String[] args)
{
ExceptTestFrame frame = new ExceptTestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame with a panel for testing various exceptions
*/
class ExceptTestFrame extends JFrame
{
public ExceptTestFrame()
{
setTitle("ExceptTest");
ExceptTestPanel panel = new ExceptTestPanel();
add(panel);
pack();
}
}
/**
A panel with radio buttons for running code snippets
and studying their exception behavior
*/
class ExceptTestPanel extends Box
{
public ExceptTestPanel()
{
super(BoxLayout.Y_AXIS);
group = new ButtonGroup();
// add radio buttons for code snippets
addRadioButton("Integer divide by zero", new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
a[1] = 1 / (a.length - a.length);
}
});
addRadioButton("Floating point divide by zero", new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
a[1] = a[2] / (a[3] - a[3]);
}
});
addRadioButton("Array bounds", new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
a[1] = a[10];
}
});
addRadioButton("Bad cast", new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
a = (double[])event.getSource();
}
});
addRadioButton("Null pointer", new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
event = null;
System.out.println(event.getSource());
}
});
addRadioButton("sqrt(-1)", new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
a[1] = Math.sqrt(-1);
}
});
addRadioButton("Overflow", new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
a[1] = 1000 * 1000 * 1000 * 1000;
int n = (int) a[1];
}
});
addRadioButton("No such file", new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
InputStream in = new FileInputStream("woozle.txt");
}
catch (IOException e)
{
textField.setText(e.toString());
}
}
});
addRadioButton("Throw unknown", new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
throw new UnknownError();
}
});
// add the text field for exception display
textField = new JTextField(30);
add(textField);
}
/**
Adds a radio button with a given listener to the
panel. Traps any exceptions in the actionPerformed
method of the listener.
@param s the label of the radio button
@param listener the action listener for the radio button
*/
private void addRadioButton(String s, ActionListener listener)
{
JRadioButton button = new JRadioButton(s, false)
{
// the button calls this method to fire an
// action event. We override it to trap exceptions
protected void fireActionPerformed(ActionEvent event)
{
try
{
textField.setText("No exception");
super.fireActionPerformed(event);
}
catch (Exception e)
{
textField.setText(e.toString());
}
}
};
button.addActionListener(listener);
add(button);
group.add(button);
}
private ButtonGroup group;
private JTextField textField;
private double[] a = new double[10];
}
@@ -0,0 +1,43 @@
/**
@version 1.10 2000-06-03
@author Cay Horstmann
*/
import java.util.*;
public class ExceptionalTest
{
public static void main(String[] args)
{
int i = 0;
int ntry = 1000000;
Stack s = new Stack();
long s1;
long s2;
// test a stack for emptiness ntry times
System.out.println("Testing for empty stack");
s1 = new Date().getTime();
for (i = 0; i <= ntry; i++)
if (!s.empty()) s.pop();
s2 = new Date().getTime();
System.out.println((s2 - s1) + " milliseconds");
// pop an empty stack ntry times and catch the
// resulting exception
System.out.println("Catching EmptyStackException");
s1 = new Date().getTime();
for (i = 0; i <= ntry; i++)
{
try
{
s.pop();
}
catch(EmptyStackException e)
{
}
}
s2 = new Date().getTime();
System.out.println((s2 - s1) + " milliseconds");
}
}
@@ -0,0 +1,167 @@
/**
@version 1.01 2004-05-10
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.util.logging.*;
import javax.swing.*;
/**
A modification of the image viewer program that logs
various events.
*/
public class LoggingImageViewer
{
public static void main(String[] args)
{
if (System.getProperty("java.util.logging.config.class") == null
&& System.getProperty("java.util.logging.config.file") == null)
{
try
{
Logger.getLogger("").setLevel(Level.ALL);
final int LOG_ROTATION_COUNT = 10;
Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
Logger.getLogger("").addHandler(handler);
}
catch (IOException e)
{
Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE,
"Can't create log file handler", e);
}
}
Handler windowHandler = new WindowHandler();
windowHandler.setLevel(Level.ALL);
Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);
JFrame frame = new ImageViewerFrame();
frame.setTitle("LoggingImageViewer");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Logger.getLogger("com.horstmann.corejava").fine("Showing frame");
frame.setVisible(true);
}
}
/**
The frame that shows the image.
*/
class ImageViewerFrame extends JFrame
{
public ImageViewerFrame()
{
logger.entering("ImageViewerFrame", "<init>");
// set up menu bar
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(new FileOpenListener());
JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
logger.fine("Exiting.");
System.exit(0);
}
});
// use a label to display the images
label = new JLabel();
add(label);
logger.exiting("ImageViewerFrame", "<init>");
}
private class FileOpenListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event);
// set up file chooser
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
// accept all files ending with .gif
chooser.setFileFilter(new
javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
}
public String getDescription()
{
return "GIF Images";
}
});
// show file chooser dialog
int r = chooser.showOpenDialog(ImageViewerFrame.this);
// if image file accepted, set it as icon of the label
if (r == JFileChooser.APPROVE_OPTION)
{
String name = chooser.getSelectedFile().getPath();
logger.log(Level.FINE, "Reading file {0}", name);
label.setIcon(new ImageIcon(name));
}
else
logger.fine("File open dialog canceled.");
logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed");
}
}
private JLabel label;
private static Logger logger = Logger.getLogger("com.horstmann.corejava");
}
/**
A handler for displaying log records in a window.
*/
class WindowHandler extends StreamHandler
{
public WindowHandler()
{
frame = new JFrame();
final JTextArea output = new JTextArea();
output.setEditable(false);
frame.setSize(200, 200);
frame.add(new JScrollPane(output));
frame.setFocusableWindowState(false);
frame.setVisible(true);
setOutputStream(new
OutputStream()
{
public void write(int b) {} // not called
public void write(byte[] b, int off, int len)
{
output.append(new String(b, off, len));
}
});
}
public void publish(LogRecord record)
{
if (!frame.isVisible()) return;
super.publish(record);
flush();
}
private JFrame frame;
}
@@ -0,0 +1,27 @@
/**
@version 1.31 2004-05-11
@author Cay Horstmann
*/
import java.awt.*;
import javax.swing.*;
/**
A frame with a button panel
*/
class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("ButtonTest");
setSize(WIDTH, HEIGHT);
// add panel to frame
ButtonPanel panel = new ButtonPanel();
add(panel);
}
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
}
@@ -0,0 +1,60 @@
/**
@version 1.32 2004-05-11
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
A panel with three buttons
*/
class ButtonPanel extends JPanel
{
public ButtonPanel()
{
// create buttons
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");
// add buttons to panel
add(yellowButton);
add(blueButton);
add(redButton);
// create button actions
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED);
// associate actions with buttons
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
/**
An action listener that sets the panel's background color.
*/
private class ColorAction implements ActionListener
{
public ColorAction(Color c)
{
backgroundColor = c;
}
public void actionPerformed(ActionEvent event)
{
setBackground(backgroundColor);
}
private Color backgroundColor;
}
}
@@ -0,0 +1,88 @@
/**
@version 1.02 2004-05-11
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class RobotTest
{
public static void main(String[] args)
{
// make frame with a button panel
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// attach a robot to the screen device
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice screen = environment.getDefaultScreenDevice();
try
{
Robot robot = new Robot(screen);
run(robot);
}
catch (AWTException e)
{
e.printStackTrace();
}
}
/**
Runs a sample test procedure
@param robot the robot attached to the screen device
*/
public static void run(Robot robot)
{
// simulate a space bar press
robot.keyPress(' ');
robot.keyRelease(' ');
// simulate a tab key followed by a space
robot.delay(2000);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(' ');
robot.keyRelease(' ');
// simulate a mouse click over the rightmost button
robot.delay(2000);
robot.mouseMove(200, 50);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
// capture the screen and show the resulting image
robot.delay(2000);
BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0, 400, 300));
ImageFrame frame = new ImageFrame(image);
frame.setVisible(true);
}
}
/**
A frame to display a captured image
*/
class ImageFrame extends JFrame
{
/**
@param image the image to display
*/
public ImageFrame(Image image)
{
setTitle("Capture");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
JLabel label = new JLabel(new ImageIcon(image));
add(label);
}
public static final int DEFAULT_WIDTH = 450;
public static final int DEFAULT_HEIGHT = 350;
}
@@ -0,0 +1,40 @@
/**
@version 1.01 2004-05-10
@author Cay Horstmann
*/
import java.util.*;
/**
A program that displays a trace feature of a recursive
method call.
*/
public class StackTraceTest
{
/**
Computes the factorial of a number
@param n a nonnegative integer
@return n! = 1 * 2 * . . . * n
*/
public static int factorial(int n)
{
System.out.println("factorial(" + n + "):");
Throwable t = new Throwable();
StackTraceElement[] frames = t.getStackTrace();
for (StackTraceElement f : frames)
System.out.println(f);
int r;
if (n <= 1) r = 1;
else r = n * factorial(n - 1);
System.out.println("return " + r);
return r;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
factorial(n);
}
}
@@ -0,0 +1,155 @@
/**
@version 1.11 2004-05-11
@author Cay Horstmann
*/
import java.io.*;
import java.util.*;
public class DataFileTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
try
{
// save all employee records to the file employee.dat
PrintWriter out = new PrintWriter(new FileWriter("employee.dat"));
writeData(staff, out);
out.close();
// retrieve all records into a new array
BufferedReader in = new BufferedReader(new FileReader("employee.dat"));
Employee[] newStaff = readData(in);
in.close();
// print the newly read employee records
for (Employee e : newStaff)
System.out.println(e);
}
catch(IOException exception)
{
exception.printStackTrace();
}
}
/**
Writes all employees in an array to a print writer
@param employees an array of employees
@param out a print writer
*/
static void writeData(Employee[] employees, PrintWriter out)
throws IOException
{
// write number of employees
out.println(employees.length);
for (Employee e : employees)
e.writeData(out);
}
/**
Reads an array of employees from a buffered reader
@param in the buffered reader
@return the array of employees
*/
static Employee[] readData(BufferedReader in)
throws IOException
{
// retrieve the array size
int n = Integer.parseInt(in.readLine());
Employee[] employees = new Employee[n];
for (int i = 0; i < n; i++)
{
employees[i] = new Employee();
employees[i].readData(in);
}
return employees;
}
}
class Employee
{
public Employee() {}
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString()
{
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
}
/**
Writes employee data to a print writer
@param out the print writer
*/
public void writeData(PrintWriter out) throws IOException
{
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(hireDay);
out.println(name + "|"
+ salary + "|"
+ calendar.get(Calendar.YEAR) + "|"
+ (calendar.get(Calendar.MONTH) + 1) + "|"
+ calendar.get(Calendar.DAY_OF_MONTH));
}
/**
Reads employee data from a buffered reader
@param in the buffered reader
*/
public void readData(BufferedReader in) throws IOException
{
String s = in.readLine();
StringTokenizer t = new StringTokenizer(s, "|");
name = t.nextToken();
salary = Double.parseDouble(t.nextToken());
int y = Integer.parseInt(t.nextToken());
int m = Integer.parseInt(t.nextToken());
int d = Integer.parseInt(t.nextToken());
GregorianCalendar calendar = new GregorianCalendar(y, m - 1, d);
hireDay = calendar.getTime();
}
private String name;
private double salary;
private Date hireDay;
}
@@ -0,0 +1,40 @@
/**
@version 1.00 05 Sep 1997
@author Gary Cornell
*/
import java.io.*;
public class FindDirectories
{
public static void main(String[] args)
{
// if no arguments provided, start at the parent directory
if (args.length == 0) args = new String[] { ".." };
try
{
File pathName = new File(args[0]);
String[] fileNames = pathName.list();
// enumerate all files in the directory
for (int i = 0; i < fileNames.length; i++)
{
File f = new File(pathName.getPath(), fileNames[i]);
// if the file is again a directory, call the main method recursively
if (f.isDirectory())
{
System.out.println(f.getCanonicalPath());
main(new String [] { f.getPath() });
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
@@ -0,0 +1,57 @@
/**
@version 1.01 2004-06-04
@author Cay Horstmann
*/
import java.io.*;
import java.net.*;
import java.util.regex.*;
/**
This program displays all URLs in a web page by
matching a regular expression that describes the
<a href=...> HTML tag. Start the program as
java HrefMatch URL
*/
public class HrefMatch
{
public static void main(String[] args)
{
try
{
// get URL string from command line or use default
String urlString;
if (args.length > 0) urlString = args[0];
else urlString = "http://java.sun.com";
// open reader for URL
InputStreamReader in = new InputStreamReader(new URL(urlString).openStream());
// read contents into string buffer
StringBuilder input = new StringBuilder();
int ch;
while ((ch = in.read()) != -1) input.append((char) ch);
// search for all occurrences of pattern
String patternString = "<a\\s+href\\s*=\\s*(\"[^\"]*\"|[^\\s>])\\s*>";
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
while (matcher.find())
{
int start = matcher.start();
int end = matcher.end();
String match = input.substring(start, end);
System.out.println(match);
}
}
catch (IOException e)
{
e.printStackTrace();
}
catch (PatternSyntaxException e)
{
e.printStackTrace();
}
}
}
+106
View File
@@ -0,0 +1,106 @@
/**
@version 1.01 2004-05-11
@author Cay Horstmann
*/
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.zip.*;
/**
This program computes the CRC checksum of a file.
Usage: java NIOTest filename
*/
public class NIOTest
{
public static long checksumInputStream(String filename)
throws IOException
{
InputStream in = new FileInputStream(filename);
CRC32 crc = new CRC32();
int c;
while((c = in.read()) != -1)
crc.update(c);
return crc.getValue();
}
public static long checksumBufferedInputStream(String filename)
throws IOException
{
InputStream in = new BufferedInputStream(new FileInputStream(filename));
CRC32 crc = new CRC32();
int c;
while((c = in.read()) != -1)
crc.update(c);
return crc.getValue();
}
public static long checksumRandomAccessFile(String filename)
throws IOException
{
RandomAccessFile file = new RandomAccessFile(filename, "r");
long length = file.length();
CRC32 crc = new CRC32();
for (long p = 0; p < length; p++)
{
file.seek(p);
int c = file.readByte();
crc.update(c);
}
return crc.getValue();
}
public static long checksumMappedFile(String filename)
throws IOException
{
FileInputStream in = new FileInputStream(filename);
FileChannel channel = in.getChannel();
CRC32 crc = new CRC32();
int length = (int) channel.size();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
for (int p = 0; p < length; p++)
{
int c = buffer.get(p);
crc.update(c);
}
return crc.getValue();
}
public static void main(String[] args)
throws IOException
{
System.out.println("Input Stream:");
long start = System.currentTimeMillis();
long crcValue = checksumInputStream(args[0]);
long end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end - start) + " milliseconds");
System.out.println("Buffered Input Stream:");
start = System.currentTimeMillis();
crcValue = checksumBufferedInputStream(args[0]);
end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end - start) + " milliseconds");
System.out.println("Random Access File:");
start = System.currentTimeMillis();
crcValue = checksumRandomAccessFile(args[0]);
end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end - start) + " milliseconds");
System.out.println("Mapped File:");
start = System.currentTimeMillis();
crcValue = checksumMappedFile(args[0]);
end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end - start) + " milliseconds");
}
}
@@ -0,0 +1,127 @@
/**
@version 1.11 2004-05-11
@author Cay Horstmann
*/
import java.io.*;
import java.util.*;
class ObjectFileTest
{
public static void main(String[] args)
{
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
Employee[] staff = new Employee[3];
staff[0] = boss;
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
try
{
// save all employee records to the file employee.dat
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"));
out.writeObject(staff);
out.close();
// retrieve all records into a new array
ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"));
Employee[] newStaff = (Employee[]) in.readObject();
in.close();
// print the newly read employee records
for (Employee e : newStaff)
System.out.println(e);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
class Employee implements Serializable
{
public Employee() {}
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString()
{
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
}
private String name;
private double salary;
private Date hireDay;
}
class Manager extends Employee
{
/**
@param n the employee's name
@param s the salary
@param year the hire year
@param month the hire month
@param day the hire day
*/
public Manager(String n, double s, int year, int month, int day)
{
super(n, s, year, month, day);
bonus = 0;
}
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}
public String toString()
{
return super.toString()
+ "[bonus=" + bonus
+ "]";
}
private double bonus;
}
@@ -0,0 +1,131 @@
/**
@version 1.10 17 Aug 1998
@author Cay Horstmann
*/
import java.io.*;
import java.util.*;
class ObjectRefTest
{
public static void main(String[] args)
{
Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setSecretary(harry);
Employee[] staff = new Employee[3];
staff[0] = boss;
staff[1] = harry;
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
try
{
// save all employee records to the file employee.dat
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"));
out.writeObject(staff);
out.close();
// retrieve all records into a new array
ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"));
Employee[] newStaff = (Employee[]) in.readObject();
in.close();
// raise secretary's salary
newStaff[1].raiseSalary(10);
// print the newly read employee records
for (Employee e : newStaff)
System.out.println(e);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
class Employee implements Serializable
{
public Employee() {}
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString()
{
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
}
private String name;
private double salary;
private Date hireDay;
}
class Manager extends Employee
{
/**
Constructs a Manager without a secretary
@param n the employee's name
@param s the salary
@param year the hire year
@param month the hire month
@param day the hire day
*/
public Manager(String n, double s, int year, int month, int day)
{
super(n, s, year, month, day);
secretary = null;
}
/**
Assigns a secretary to the manager.
@param s the secretary
*/
public void setSecretary(Employee s)
{
secretary = s;
}
public String toString()
{
return super.toString()
+ "[secretary=" + secretary
+ "]";
}
private Employee secretary;
}
@@ -0,0 +1,168 @@
/**
@version 1.11 2004-05-11
@author Cay Horstmann
*/
import java.io.*;
import java.util.*;
public class RandomFileTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
try
{
// save all employee records to the file employee.dat
DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat"));
for (Employee e : staff)
e.writeData(out);
out.close();
// retrieve all records into a new array
RandomAccessFile in = new RandomAccessFile("employee.dat", "r");
// compute the array size
int n = (int)(in.length() / Employee.RECORD_SIZE);
Employee[] newStaff = new Employee[n];
// read employees in reverse order
for (int i = n - 1; i >= 0; i--)
{
newStaff[i] = new Employee();
in.seek(i * Employee.RECORD_SIZE);
newStaff[i].readData(in);
}
in.close();
// print the newly read employee records
for (Employee e : newStaff)
System.out.println(e);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class Employee
{
public Employee() {}
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
/**
Raises the salary of this employee.
@byPercent the percentage of the raise
*/
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString()
{
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
}
/**
Writes employee data to a data output
@param out the data output
*/
public void writeData(DataOutput out) throws IOException
{
DataIO.writeFixedString(name, NAME_SIZE, out);
out.writeDouble(salary);
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(hireDay);
out.writeInt(calendar.get(Calendar.YEAR));
out.writeInt(calendar.get(Calendar.MONTH) + 1);
out.writeInt(calendar.get(Calendar.DAY_OF_MONTH));
}
/**
Reads employee data from a data input
@param in the data input
*/
public void readData(DataInput in) throws IOException
{
name = DataIO.readFixedString(NAME_SIZE, in);
salary = in.readDouble();
int y = in.readInt();
int m = in.readInt();
int d = in.readInt();
GregorianCalendar calendar = new GregorianCalendar(y, m - 1, d);
hireDay = calendar.getTime();
}
public static final int NAME_SIZE = 40;
public static final int RECORD_SIZE = 2 * NAME_SIZE + 8 + 4 + 4 + 4;
private String name;
private double salary;
private Date hireDay;
}
class DataIO
{
public static String readFixedString(int size, DataInput in)
throws IOException
{
StringBuilder b = new StringBuilder(size);
int i = 0;
boolean more = true;
while (more && i < size)
{
char ch = in.readChar();
i++;
if (ch == 0) more = false;
else b.append(ch);
}
in.skipBytes(2 * (size - i));
return b.toString();
}
public static void writeFixedString(String s, int size, DataOutput out)
throws IOException
{
for (int i = 0; i < size; i++)
{
char ch = 0;
if (i < s.length()) ch = s.charAt(i);
out.writeChar(ch);
}
}
}
@@ -0,0 +1,64 @@
/**
@version 1.01 2004-05-11
@author Cay Horstmann
*/
import java.util.*;
import java.util.regex.*;
/**
This program tests regular expression matching.
Enter a pattern and strings to match, or hit Cancel
to exit. If the pattern contains groups, the group
boundaries are displayed in the match.
*/
public class RegExTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter pattern: ");
String patternString = in.nextLine();
Pattern pattern = null;
try
{
pattern = Pattern.compile(patternString);
}
catch (PatternSyntaxException e)
{
System.out.println("Pattern syntax error");
System.exit(1);
}
while (true)
{
System.out.println("Enter string to match: ");
String input = in.nextLine();
if (input == null || input.equals("")) return;
Matcher matcher = pattern.matcher(input);
if (matcher.matches())
{
System.out.println("Match");
int g = matcher.groupCount();
if (g > 0)
{
for (int i = 0; i < input.length(); i++)
{
for (int j = 1; j <= g; j++)
if (i == matcher.start(j))
System.out.print('(');
System.out.print(input.charAt(i));
for (int j = 1; j <= g; j++)
if (i + 1 == matcher.end(j))
System.out.print(')');
}
System.out.println();
}
}
else
System.out.println("No match");
}
}
}
@@ -0,0 +1,106 @@
/**
@version 1.20 17 Aug 1998
@author Cay Horstmann
*/
import java.io.*;
import java.util.*;
public class SerialCloneTest
{
public static void main(String[] args)
{
Employee harry = new Employee("Harry Hacker", 35000, 1989, 10, 1);
// clone harry
Employee harry2 = (Employee) harry.clone();
// mutate harry
harry.raiseSalary(10);
// now harry and the clone are different
System.out.println(harry);
System.out.println(harry2);
}
}
/**
A class whose clone method uses serialization.
*/
class SerialCloneable implements Cloneable, Serializable
{
public Object clone()
{
try
{
// save the object to a byte array
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(this);
out.close();
// read a clone of the object from the byte array
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bin);
Object ret = in.readObject();
in.close();
return ret;
}
catch (Exception e)
{
return null;
}
}
}
/**
The familiar Employee class, redefined to extend the
SerialCloneable class.
*/
class Employee extends SerialCloneable
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString()
{
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
}
private String name;
private double salary;
private Date hireDay;
}
@@ -0,0 +1,218 @@
/**
@version 1.31 2004-05-11
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
public class ZipTest
{
public static void main(String[] args)
{
ZipTestFrame frame = new ZipTestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame with a text area to show the contents of a file inside
a zip archive, a combo box to select different files in the
archive, and a menu to load a new archive.
*/
class ZipTestFrame extends JFrame
{
public ZipTestFrame()
{
setTitle("ZipTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add the menu and the Open and Exit menu items
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(new OpenAction());
JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
menuBar.add(menu);
setJMenuBar(menuBar);
// add the text area and combo box
fileText = new JTextArea();
fileCombo = new JComboBox();
fileCombo.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
loadZipFile((String) fileCombo.getSelectedItem());
}
});
add(fileCombo, BorderLayout.SOUTH);
add(new JScrollPane(fileText), BorderLayout.CENTER);
}
/**
This is the listener for the File->Open menu item.
*/
private class OpenAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// prompt the user for a zip file
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
ExtensionFileFilter filter = new ExtensionFileFilter();
filter.addExtension(".zip");
filter.addExtension(".jar");
filter.setDescription("ZIP archives");
chooser.setFileFilter(filter);
int r = chooser.showOpenDialog(ZipTestFrame.this);
if (r == JFileChooser.APPROVE_OPTION)
{
zipname = chooser.getSelectedFile().getPath();
scanZipFile();
}
}
}
/**
Scans the contents of the zip archive and populates
the combo box.
*/
public void scanZipFile()
{
fileCombo.removeAllItems();
try
{
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null)
{
fileCombo.addItem(entry.getName());
zin.closeEntry();
}
zin.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
Loads a file from the zip archive into the text area
@param name the name of the file in the archive
*/
public void loadZipFile(String name)
{
try
{
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
ZipEntry entry;
fileText.setText("");
// find entry with matching name in archive
while ((entry = zin.getNextEntry()) != null)
{
if (entry.getName().equals(name))
{
// read entry into text area
BufferedReader in = new BufferedReader(new InputStreamReader(zin));
String line;
while ((line = in.readLine()) != null)
{
fileText.append(line);
fileText.append("\n");
}
}
zin.closeEntry();
}
zin.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 300;
private JComboBox fileCombo;
private JTextArea fileText;
private String zipname;
}
/**
This file filter matches all files with a given set of
extensions. From FileChooserTest in chapter 9
*/
class ExtensionFileFilter extends FileFilter
{
/**
Adds an extension that this file filter recognizes.
@param extension a file extension (such as ".txt" or "txt")
*/
public void addExtension(String extension)
{
if (!extension.startsWith("."))
extension = "." + extension;
extensions.add(extension.toLowerCase());
}
/**
Sets a description for the file set that this file filter
recognizes.
@param aDescription a description for the file set
*/
public void setDescription(String aDescription)
{
description = aDescription;
}
/**
Returns a description for the file set that this file
filter recognizes.
@return a description for the file set
*/
public String getDescription()
{
return description;
}
public boolean accept(File f)
{
if (f.isDirectory()) return true;
String name = f.getName().toLowerCase();
// check if the file name ends with any of the extensions
for (String e : extensions)
if (name.endsWith(e))
return true;
return false;
}
private String description = "";
private ArrayList<String> extensions = new ArrayList<String>();
}
@@ -0,0 +1,110 @@
import java.lang.reflect.*;
import java.util.*;
public class GenericReflectionTest
{
public static void main(String[] args)
{
// read class name from command line args or user input
String name;
if (args.length > 0)
name = args[0];
else
{
Scanner in = new Scanner(System.in);
System.out.println("Enter class name (e.g. java.util.Date): ");
name = in.next();
}
try
{
// print generic info for class and public methods
Class cl = Class.forName(name);
printClass(cl);
for (Method m : cl.getDeclaredMethods())
printMethod(m);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public static void printClass(Class cl)
{
System.out.print(cl);
printTypes(cl.getTypeParameters(), "<", ", ", ">");
Type sc = cl.getGenericSuperclass();
if (sc != null)
{
System.out.print(" extends ");
printType(sc);
}
printTypes(cl.getGenericInterfaces(), " implements ", ", ", "");
System.out.println();
}
public static void printMethod(Method m)
{
String name = m.getName();
System.out.print(Modifier.toString(m.getModifiers()));
System.out.print(" ");
printTypes(m.getTypeParameters(), "<", ", ", "> ");
printType(m.getGenericReturnType());
System.out.print(" ");
System.out.print(name);
System.out.print("(");
printTypes(m.getGenericParameterTypes(), "", ", ", "");
System.out.println(")");
}
public static void printTypes(Type[] types, String pre, String sep, String suf)
{
if (types.length > 0) System.out.print(pre);
for (int i = 0; i < types.length; i++)
{
if (i > 0) System.out.print(sep);
printType(types[i]);
}
if (types.length > 0) System.out.print(suf);
}
public static void printType(Type type)
{
if (type instanceof Class)
{
Class t = (Class) type;
System.out.print(t.getName());
}
else if (type instanceof TypeVariable)
{
TypeVariable t = (TypeVariable) type;
System.out.print(t.getName());
printTypes(t.getBounds(), " extends ", " & ", "");
}
else if (type instanceof WildcardType)
{
WildcardType t = (WildcardType) type;
System.out.print("?");
printTypes(t.getLowerBounds(), " extends ", " & ", "");
printTypes(t.getUpperBounds(), " super ", " & ", "");
}
else if (type instanceof ParameterizedType)
{
ParameterizedType t = (ParameterizedType) type;
Type owner = t.getOwnerType();
if (owner != null) { printType(owner); System.out.print("."); }
printType(t.getRawType());
printTypes(t.getActualTypeArguments(), "<", ", ", ">");
}
else if (type instanceof GenericArrayType)
{
GenericArrayType t = (GenericArrayType) type;
System.out.print("");
printType(t.getGenericComponentType());
System.out.print("[]");
}
}
}
@@ -0,0 +1,18 @@
/**
@version 1.00 2004-05-10
@author Cay Horstmann
*/
public class Pair<T>
{
public Pair() { first = null; second = null; }
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
private T first;
private T second;
}
@@ -0,0 +1,32 @@
public class PairTest1
{
public static void main(String[] args)
{
String[] words = { "Mary", "had", "a", "little", "lamb" };
Pair<String> mm = ArrayAlg.minmax(words);
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
}
}
class ArrayAlg
{
/**
Gets the minimum and maximum of an array of strings.
@param a an array of strings
@return a pair with the min and max value, or null if a is
null or empty
*/
public static Pair<String> minmax(String[] a)
{
if (a == null || a.length == 0) return null;
String min = a[0];
String max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.compareTo(a[i]) > 0) min = a[i];
if (max.compareTo(a[i]) < 0) max = a[i];
}
return new Pair<String>(min, max);
}
}
@@ -0,0 +1,18 @@
/**
@version 1.00 2004-05-10
@author Cay Horstmann
*/
public class Pair<T>
{
public Pair() { first = null; second = null; }
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
private T first;
private T second;
}
@@ -0,0 +1,40 @@
import java.util.*;
public class PairTest2
{
public static void main(String[] args)
{
GregorianCalendar[] birthdays =
{
new GregorianCalendar(1906, Calendar.DECEMBER, 9), // G. Hopper
new GregorianCalendar(1815, Calendar.DECEMBER, 10), // A. Lovelace
new GregorianCalendar(1903, Calendar.DECEMBER, 3), // J. von Neumann
new GregorianCalendar(1910, Calendar.JUNE, 22), // K. Zuse
};
Pair<GregorianCalendar> mm = ArrayAlg.minmax(birthdays);
System.out.println("min = " + mm.getFirst().getTime());
System.out.println("max = " + mm.getSecond().getTime());
}
}
class ArrayAlg
{
/**
Gets the minimum and maximum of an array of objects of type T.
@param a an array of objects of type T
@return a pair with the min and max value, or null if a is
null or empty
*/
public static <T extends Comparable> Pair<T> minmax(T[] a)
{
if (a == null || a.length == 0) return null;
T min = a[0];
T max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.compareTo(a[i]) > 0) min = a[i];
if (max.compareTo(a[i]) < 0) max = a[i];
}
return new Pair<T>(min, max);
}
}
@@ -0,0 +1,31 @@
/**
@version 1.21 2004-02-21
@author Cay Horstmann
*/
import java.util.*;
public class ManagerTest
{
public static void main(String[] args)
{
// construct a Manager object
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
Employee[] staff = new Employee[3];
// fill the staff array with Manager and Employee objects
staff[0] = boss;
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName()
+ ",salary=" + e.getSalary());
}
}
@@ -0,0 +1,18 @@
/**
@version 1.00 2004-05-10
@author Cay Horstmann
*/
public class Pair<T>
{
public Pair() { first = null; second = null; }
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
private T first;
private T second;
}
@@ -0,0 +1,139 @@
import java.util.*;
public class PairTest3
{
public static void main(String[] args)
{
Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
Pair<Manager> buddies = new Pair<Manager>(ceo, cfo);
printBuddies(buddies);
ceo.setBonus(1000000);
cfo.setBonus(500000);
Manager[] managers = { ceo, cfo };
Pair<Employee> result = new Pair<Employee>();
minMaxBonus(managers, result);
System.out.println("first: " + result.getFirst().getName()
+ ", second: " + result.getSecond().getName());
maxMinBonus(managers, result);
System.out.println("first: " + result.getFirst().getName()
+ ", second: " + result.getSecond().getName());
}
public static void printBuddies(Pair<? extends Employee> p)
{
Employee first = p.getFirst();
Employee second = p.getSecond();
System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
}
public static void minMaxBonus(Manager[] a, Pair<? super Manager> result)
{
if (a == null || a.length == 0) return;
Manager min = a[0];
Manager max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.getBonus() > a[i].getBonus()) min = a[i];
if (max.getBonus() < a[i].getBonus()) max = a[i];
}
result.setFirst(min);
result.setSecond(max);
}
public static void maxMinBonus(Manager[] a, Pair<? super Manager> result)
{
minMaxBonus(a, result);
PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type
}
}
class PairAlg
{
public static boolean hasNulls(Pair<?> p)
{
return p.getFirst() == null || p.getSecond() == null;
}
public static void swap(Pair<?> p) { swapHelper(p); }
public static <T> void swapHelper(Pair<T> p)
{
T t = p.getFirst();
p.setFirst(p.getSecond());
p.setSecond(t);
}
}
class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
private String name;
private double salary;
private Date hireDay;
}
class Manager extends Employee
{
/**
@param n the employee's name
@param s the salary
@param year the hire year
@param month the hire month
@param day the hire day
*/
public Manager(String n, double s, int year, int month, int day)
{
super(n, s, year, month, day);
bonus = 0;
}
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}
public double getBonus()
{
return bonus;
}
private double bonus;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

@@ -0,0 +1,84 @@
/**
@version 1.22 2004-05-21
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
/**
A program for viewing images.
*/
public class ImageViewer
{
public static void main(String[] args)
{
JFrame frame = new ImageViewerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame with a label to show an image.
*/
class ImageViewerFrame extends JFrame
{
public ImageViewerFrame()
{
setTitle("ImageViewer");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// use a label to display the images
label = new JLabel();
add(label);
// set up the file chooser
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
// set up the menu bar
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
// show file chooser dialog
int result = chooser.showOpenDialog(null);
// if file selected, set it as icon of the label
if (result == JFileChooser.APPROVE_OPTION)
{
String name = chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
}
}
});
JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
}
private JLabel label;
private JFileChooser chooser;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 400;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

@@ -0,0 +1,18 @@
/**
@version 1.20 2004-02-28
@author Cay Horstmann
*/
public class Welcome
{
public static void main(String[] args)
{
String[] greeting = new String[3];
greeting[0] = "Welcome to Core Java";
greeting[1] = "by Cay Horstmann";
greeting[2] = "and Gary Cornell";
for (String g : greeting)
System.out.println(g);
}
}
@@ -0,0 +1,19 @@
<html>
<head>
<title>WelcomeApplet</title>
</head>
<body>
<hr/>
<p>
This applet is from the book
<a href="http://www.horstmann.com/corejava.html">Core Java</a>
by <em>Cay Horstmann</em> and <em>Gary Cornell</em>,
published by Sun Microsystems Press.
</p>
<applet code="WelcomeApplet.class" width="400" height="200">
<param name="greeting" value ="Welcome to Core Java!"/>
</applet>
<hr/>
<p><a href="WelcomeApplet.java">The source.</a></p>
</body>
</html>
@@ -0,0 +1,54 @@
/**
@version 1.21 2002-06-19
@author Cay Horstmann
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class WelcomeApplet extends JApplet
{
public void init()
{
setLayout(new BorderLayout());
JLabel label = new JLabel(getParameter("greeting"), SwingConstants.CENTER);
label.setFont(new Font("Serif", Font.BOLD, 18));
add(label, BorderLayout.CENTER);
JPanel panel = new JPanel();
JButton cayButton = new JButton("Cay Horstmann");
cayButton.addActionListener(makeURLActionListener(
"http://www.horstmann.com"));
panel.add(cayButton);
JButton garyButton = new JButton("Gary Cornell");
garyButton.addActionListener(makeURLActionListener(
"mailto:gary@thecornells.com"));
panel.add(garyButton);
add(panel, BorderLayout.SOUTH);
}
private ActionListener makeURLActionListener(final String u)
{
return new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
getAppletContext().showDocument(new URL(u));
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
}
};
}
}
@@ -0,0 +1,37 @@
/**
@version 1.20 2004-02-10
@author Cay Horstmann
*/
import java.math.*;
import java.util.*;
public class BigIntegerTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you need to draw? ");
int k = in.nextInt();
System.out.print("What is the highest number you can draw? ");
int n = in.nextInt();
/*
compute binomial coefficient
n * (n - 1) * (n - 2) * . . . * (n - k + 1)
-------------------------------------------
1 * 2 * 3 * . . . * k
*/
BigInteger lotteryOdds = BigInteger.valueOf(1);
for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds
.multiply(BigInteger.valueOf(n - i + 1))
.divide(BigInteger.valueOf(i));
System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
}
}
@@ -0,0 +1,57 @@
/**
@version 1.40 2004-02-10
@author Cay Horstmann
*/
public class CompoundInterest
{
public static void main(String[] args)
{
final double STARTRATE = 10;
final int NRATES = 6;
final int NYEARS = 10;
// set interest rates to 10 . . . 15%
double[] interestRate = new double[NRATES];
for (int j = 0; j < interestRate.length; j++)
interestRate[j] = (STARTRATE + j) / 100.0;
double[][] balances = new double[NYEARS][NRATES];
// set initial balances to 10000
for (int j = 0; j < balances[0].length; j++)
balances[0][j] = 10000;
// compute interest for future years
for (int i = 1; i < balances.length; i++)
{
for (int j = 0; j < balances[i].length; j++)
{
// get last year's balances from previous row
double oldBalance = balances[i - 1][j];
// compute interest
double interest = oldBalance * interestRate[j];
// compute this year's balances
balances[i][j] = oldBalance + interest;
}
}
// print one row of interest rates
for (int j = 0; j < interestRate.length; j++)
System.out.printf("%9.0f%%", 100 * interestRate[j]);
System.out.println();
// print balance table
for (double[] row : balances)
{
// print table row
for (double b : row)
System.out.printf("%10.2f", b);
System.out.println();
}
}
}
@@ -0,0 +1,17 @@
/**
@version 1.01 1997-03-22
@author Gary Cornell
*/
/*
This is the first sample program in Core Java Chapter 3
Copyright (C) 1997 Cay Horstmann and Gary Cornell
*/
public class FirstSample
{
public static void main(String[] args)
{
System.out.println("We will not use 'Hello, World!'");
}
}
@@ -0,0 +1,25 @@
/**
@version 1.10 2004-02-10
@author Cay Horstmann
*/
import java.util.*;
public class InputTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// get first input
System.out.print("What is your name? ");
String name = in.nextLine();
// get second input
System.out.print("How old are you? ");
int age = in.nextInt();
// display output on console
System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
}
}
@@ -0,0 +1,44 @@
/**
@version 1.20 2004-02-10
@author Cay Horstmann
*/
public class LotteryArray
{
public static void main(String[] args)
{
final int NMAX = 10;
// allocate triangular array
int[][] odds = new int[NMAX + 1][];
for (int n = 0; n <= NMAX; n++)
odds[n] = new int[n + 1];
// fill triangular array
for (int n = 0; n < odds.length; n++)
for (int k = 0; k < odds[n].length; k++)
{
/*
compute binomial coefficient
n * (n - 1) * (n - 2) * . . . * (n - k + 1)
-------------------------------------------
1 * 2 * 3 * . . . * k
*/
int lotteryOdds = 1;
for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds * (n - i + 1) / i;
odds[n][k] = lotteryOdds;
}
// print triangular array
for (int[] row : odds)
{
for (int odd : row)
System.out.printf("%4d", odd);
System.out.println();
}
}
}
@@ -0,0 +1,46 @@
/**
@version 1.20 2004-02-10
@author Cay Horstmann
*/
import java.util.*;
public class LotteryDrawing
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you need to draw? ");
int k = in.nextInt();
System.out.print("What is the highest number you can draw? ");
int n = in.nextInt();
// fill an array with numbers 1 2 3 . . . n
int[] numbers = new int[n];
for (int i = 0; i < numbers.length; i++)
numbers[i] = i + 1;
// draw k numbers and put them into a second array
int[] result = new int[k];
for (int i = 0; i < result.length; i++)
{
// make a random index between 0 and n - 1
int r = (int) (Math.random() * n);
// pick the element at the random location
result[i] = numbers[r];
// move the last element into the random location
numbers[r] = numbers[n - 1];
n--;
}
// print the sorted array
Arrays.sort(result);
System.out.println("Bet the following combination. It'll make you rich!");
for (int r : result)
System.out.println(r);
}
}
@@ -0,0 +1,34 @@
/**
@version 1.20 2004-02-10
@author Cay Horstmann
*/
import java.util.*;
public class LotteryOdds
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you need to draw? ");
int k = in.nextInt();
System.out.print("What is the highest number you can draw? ");
int n = in.nextInt();
/*
compute binomial coefficient
n * (n - 1) * (n - 2) * . . . * (n - k + 1)
-------------------------------------------
1 * 2 * 3 * . . . * k
*/
int lotteryOdds = 1;
for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds * (n - i + 1) / i;
System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
}
}
@@ -0,0 +1,39 @@
/**
@version 1.20 2004-02-10
@author Cay Horstmann
*/
import java.util.*;
public class Retirement
{
public static void main(String[] args)
{
// read inputs
Scanner in = new Scanner(System.in);
System.out.print("How much money do you need to retire? ");
double goal = in.nextDouble();
System.out.print("How much money will you contribute every year? ");
double payment = in.nextDouble();
System.out.print("Interest rate in %: ");
double interestRate = in.nextDouble();
double balance = 0;
int years = 0;
// update account balance while goal isn't reached
while (balance < goal)
{
// add this year's payment and interest
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
}
System.out.println("You can retire in " + years + " years.");
}
}
@@ -0,0 +1,44 @@
/**
@version 1.20 2004-02-10
@author Cay Horstmann
*/
import java.util.*;
public class Retirement2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How much money will you contribute every year? ");
double payment = in.nextDouble();
System.out.print("Interest rate in %: ");
double interestRate = in.nextDouble();
double balance = 0;
int year = 0;
String input;
// update account balance while user isn't ready to retire
do
{
// add this year's payment and interest
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;
// print current balance
System.out.printf("After year %d, your balance is %,.2f%n", year, balance);
// ask if ready to retire and get input
System.out.print("Ready to retire? (Y/N) ");
input = in.next();
}
while (input.equals("N"));
}
}
@@ -0,0 +1,57 @@
/**
@version 1.31 2004-02-19
@author Cay Horstmann
*/
import java.util.*;
public class CalendarTest
{
public static void main(String[] args)
{
// construct d as current date
GregorianCalendar d = new GregorianCalendar();
int today = d.get(Calendar.DAY_OF_MONTH);
int month = d.get(Calendar.MONTH);
// set d to start date of the month
d.set(Calendar.DAY_OF_MONTH, 1);
int weekday = d.get(Calendar.DAY_OF_WEEK);
// get first day of week (Sunday in the U.S.)
int firstDayOfWeek = d.getFirstDayOfWeek();
// indent first line of calendar
for (int i = firstDayOfWeek; i < weekday; i++ )
System.out.print(" ");
do
{
// print day
int day = d.get(Calendar.DAY_OF_MONTH);
System.out.printf("%3d", day);
// mark current day with *
if (day == today)
System.out.print("*");
else
System.out.print(" ");
// advance d to the next day
d.add(Calendar.DAY_OF_MONTH, 1);
weekday = d.get(Calendar.DAY_OF_WEEK);
// start a new line at the start of the week
if (weekday == firstDayOfWeek)
System.out.println();
}
while (d.get(Calendar.MONTH) == month);
// the loop exits when d is day 1 of the next month
// print final end of line if necessary
if (weekday != firstDayOfWeek)
System.out.println();
}
}
@@ -0,0 +1,84 @@
/**
@version 1.01 2004-02-19
@author Cay Horstmann
*/
import java.util.*;
public class ConstructorTest
{
public static void main(String[] args)
{
// fill the staff array with three Employee objects
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry", 40000);
staff[1] = new Employee(60000);
staff[2] = new Employee();
// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName()
+ ",id=" + e.getId()
+ ",salary=" + e.getSalary());
}
}
class Employee
{
// three overloaded constructors
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee(double s)
{
// calls the Employee(String, double) constructor
this("Employee #" + nextId, s);
}
// the default constructor
public Employee()
{
// name initialized to ""--see below
// salary not explicitly set--initialized to 0
// id initialized in initialization block
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
private static int nextId;
private int id;
private String name = ""; // instance field initialization
private double salary;
// static initialization block
static
{
Random generator = new Random();
// set nextId to a random number between 0 and 9999
nextId = generator.nextInt(10000);
}
// object initialization block
{
id = nextId;
nextId++;
}
}
@@ -0,0 +1,66 @@
/**
@version 1.11 2004-02-19
@author Cay Horstmann
*/
import java.util.*;
public class EmployeeTest
{
public static void main(String[] args)
{
// fill the staff array with three Employee objects
Employee[] staff = new Employee[3];
staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
// raise everyone's salary by 5%
for (Employee e : staff)
e.raiseSalary(5);
// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName()
+ ",salary=" + e.getSalary()
+ ",hireDay=" + e.getHireDay());
}
}
class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
// GregorianCalendar uses 0 for January
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
private String name;
private double salary;
private Date hireDay;
}
@@ -0,0 +1,27 @@
/**
@version 1.11 2004-02-19
@author Cay Horstmann
*/
import com.horstmann.corejava.*;
// the Employee class is defined in that package
import static java.lang.System.*;
public class PackageTest
{
public static void main(String[] args)
{
// because of the import statement, we don't have to
// use com.horstmann.corejava.Employee here
Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
// raise salary by 5%
harry.raiseSalary(5);
// print out information about harry
// use java.lang.System.out here
out.println("name=" + harry.getName() + ",salary=" + harry.getSalary());
}
}
@@ -0,0 +1,47 @@
/**
@version 1.10 1999-12-18
@author Cay Horstmann
*/
package com.horstmann.corejava;
// the classes in this file are part of this package
import java.util.*;
// import statements come after the package statement
public class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
// GregorianCalendar uses 0 for January
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
private String name;
private double salary;
private Date hireDay;
}
@@ -0,0 +1,92 @@
/**
@version 1.00 2000-01-27
@author Cay Horstmann
*/
public class ParamTest
{
public static void main(String[] args)
{
/*
Test 1: Methods can't modify numeric parameters
*/
System.out.println("Testing tripleValue:");
double percent = 10;
System.out.println("Before: percent=" + percent);
tripleValue(percent);
System.out.println("After: percent=" + percent);
/*
Test 2: Methods can change the state of object
parameters
*/
System.out.println("\nTesting tripleSalary:");
Employee harry = new Employee("Harry", 50000);
System.out.println("Before: salary=" + harry.getSalary());
tripleSalary(harry);
System.out.println("After: salary=" + harry.getSalary());
/*
Test 3: Methods can't attach new objects to
object parameters
*/
System.out.println("\nTesting swap:");
Employee a = new Employee("Alice", 70000);
Employee b = new Employee("Bob", 60000);
System.out.println("Before: a=" + a.getName());
System.out.println("Before: b=" + b.getName());
swap(a, b);
System.out.println("After: a=" + a.getName());
System.out.println("After: b=" + b.getName());
}
public static void tripleValue(double x) // doesn't work
{
x = 3 * x;
System.out.println("End of method: x=" + x);
}
public static void tripleSalary(Employee x) // works
{
x.raiseSalary(200);
System.out.println("End of method: salary="
+ x.getSalary());
}
public static void swap(Employee x, Employee y)
{
Employee temp = x;
x = y;
y = temp;
System.out.println("End of method: x=" + x.getName());
System.out.println("End of method: y=" + y.getName());
}
}
class Employee // simplified Employee class
{
public Employee(String n, double s)
{
name = n;
salary = s;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
private String name;
private double salary;
}
@@ -0,0 +1,76 @@
/**
@version 1.01 2004-02-19
@author Cay Horstmann
*/
public class StaticTest
{
public static void main(String[] args)
{
// fill the staff array with three Employee objects
Employee[] staff = new Employee[3];
staff[0] = new Employee("Tom", 40000);
staff[1] = new Employee("Dick", 60000);
staff[2] = new Employee("Harry", 65000);
// print out information about all Employee objects
for (Employee e : staff)
{
e.setId();
System.out.println("name=" + e.getName()
+ ",id=" + e.getId()
+ ",salary=" + e.getSalary());
}
int n = Employee.getNextId(); // calls static method
System.out.println("Next available id=" + n);
}
}
class Employee
{
public Employee(String n, double s)
{
name = n;
salary = s;
id = 0;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
public void setId()
{
id = nextId; // set id to next available id
nextId++;
}
public static int getNextId()
{
return nextId; // returns static field
}
public static void main(String[] args) // unit test
{
Employee e = new Employee("Harry", 50000);
System.out.println(e.getName() + " " + e.getSalary());
}
private String name;
private double salary;
private int id;
private static int nextId = 1;
}
@@ -0,0 +1,79 @@
/**
@version 1.01 2004-02-21
@author Cay Horstmann
*/
import java.lang.reflect.*;
import java.util.*;
public class ArrayGrowTest
{
public static void main(String[] args)
{
int[] a = { 1, 2, 3 };
a = (int[]) goodArrayGrow(a);
arrayPrint(a);
String[] b = { "Tom", "Dick", "Harry" };
b = (String[]) goodArrayGrow(b);
arrayPrint(b);
System.out.println("The following call will generate an exception.");
b = (String[]) badArrayGrow(b);
}
/**
This method attempts to grow an array by allocating a
new array and copying all elements.
@param a the array to grow
@return a larger array that contains all elements of a.
However, the returned array has type Object[], not
the same type as a
*/
static Object[] badArrayGrow(Object[] a)
{
int newLength = a.length * 11 / 10 + 10;
Object[] newArray = new Object[newLength];
System.arraycopy(a, 0, newArray, 0, a.length);
return newArray;
}
/**
This method grows an array by allocating a
new array of the same type and copying all elements.
@param a the array to grow. This can be an object array
or a fundamental type array
@return a larger array that contains all elements of a.
*/
static Object goodArrayGrow(Object a)
{
Class cl = a.getClass();
if (!cl.isArray()) return null;
Class componentType = cl.getComponentType();
int length = Array.getLength(a);
int newLength = length * 11 / 10 + 10;
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, length);
return newArray;
}
/**
A convenience method to print all elements in an array
@param a the array to print. can be an object array
or a fundamental type array
*/
static void arrayPrint(Object a)
{
Class cl = a.getClass();
if (!cl.isArray()) return;
Class componentType = cl.getComponentType();
int length = Array.getLength(a);
System.out.print(componentType.getName()
+ "[" + length + "] = { ");
for (int i = 0; i < Array.getLength(a); i++)
System.out.print(Array.get(a, i) + " ");
System.out.println("}");
}
}
@@ -0,0 +1,65 @@
/**
@version 1.1 2004-02-21
@author Cay Horstmann
*/
import java.util.*;
public class ArrayListTest
{
public static void main(String[] args)
{
// fill the staff array list with three Employee objects
ArrayList<Employee> staff = new ArrayList<Employee>();
staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
// raise everyone's salary by 5%
for (Employee e : staff)
e.raiseSalary(5);
// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName()
+ ",salary=" + e.getSalary()
+ ",hireDay=" + e.getHireDay());
}
}
class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
private String name;
private double salary;
private Date hireDay;
}
@@ -0,0 +1,31 @@
/**
@version 1.0 2004-05-24
@author Cay Horstmann
*/
import java.util.*;
public class EnumTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
String input = in.next().toUpperCase();
Size size = Enum.valueOf(Size.class, input);
System.out.println("size=" + size);
System.out.println("abbreviation=" + size.getAbbreviation());
if (size == Size.EXTRA_LARGE)
System.out.println("Good job--you paid attention to the _.");
}
}
enum Size
{
SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
private Size(String abbreviation) { this.abbreviation = abbreviation; }
public String getAbbreviation() { return abbreviation; }
private String abbreviation;
}
@@ -0,0 +1,153 @@
/**
@version 1.11 2004-02-21
@author Cay Horstmann
*/
import java.util.*;
public class EqualsTest
{
public static void main(String[] args)
{
Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
Employee alice2 = alice1;
Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
System.out.println("alice1 == alice2: " + (alice1 == alice2));
System.out.println("alice1 == alice3: " + (alice1 == alice3));
System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));
System.out.println("alice1.equals(bob): " + alice1.equals(bob));
System.out.println("bob.toString(): " + bob);
Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
System.out.println("boss.toString(): " + boss);
System.out.println("carl.equals(boss): " + carl.equals(boss));
System.out.println("alice1.hashCode(): " + alice1.hashCode());
System.out.println("alice3.hashCode(): " + alice3.hashCode());
System.out.println("bob.hashCode(): " + bob.hashCode());
System.out.println("carl.hashCode(): " + carl.hashCode());
}
}
class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public boolean equals(Object otherObject)
{
// a quick test to see if the objects are identical
if (this == otherObject) return true;
// must return false if the explicit parameter is null
if (otherObject == null) return false;
// if the classes don't match, they can't be equal
if (getClass() != otherObject.getClass())
return false;
// now we know otherObject is a non-null Employee
Employee other = (Employee) otherObject;
// test whether the fields have identical values
return name.equals(other.name)
&& salary == other.salary
&& hireDay.equals(other.hireDay);
}
public int hashCode()
{
return 7 * name.hashCode()
+ 11 * new Double(salary).hashCode()
+ 13 * hireDay.hashCode();
}
public String toString()
{
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
}
private String name;
private double salary;
private Date hireDay;
}
class Manager extends Employee
{
public Manager(String n, double s, int year, int month, int day)
{
super(n, s, year, month, day);
bonus = 0;
}
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}
public boolean equals(Object otherObject)
{
if (!super.equals(otherObject)) return false;
Manager other = (Manager) otherObject;
// super.equals checked that this and other belong to the same class
return bonus == other.bonus;
}
public int hashCode()
{
return super.hashCode()
+ 17 * new Double(bonus).hashCode();
}
public String toString()
{
return super.toString()
+ "[bonus=" + bonus
+ "]";
}
private double bonus;
}
@@ -0,0 +1,96 @@
/**
@version 1.21 2004-02-21
@author Cay Horstmann
*/
import java.util.*;
public class ManagerTest
{
public static void main(String[] args)
{
// construct a Manager object
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
Employee[] staff = new Employee[3];
// fill the staff array with Manager and Employee objects
staff[0] = boss;
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName()
+ ",salary=" + e.getSalary());
}
}
class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
private String name;
private double salary;
private Date hireDay;
}
class Manager extends Employee
{
/**
@param n the employee's name
@param s the salary
@param year the hire year
@param month the hire month
@param day the hire day
*/
public Manager(String n, double s, int year, int month, int day)
{
super(n, s, year, month, day);
bonus = 0;
}
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}
private double bonus;
}
@@ -0,0 +1,56 @@
/**
@version 1.1 2004-02-21
@author Cay Horstmann
*/
import java.lang.reflect.*;
public class MethodPointerTest
{
public static void main(String[] args) throws Exception
{
// get method pointers to the square and sqrt methods
Method square = MethodPointerTest.class.getMethod("square", double.class);
Method sqrt = Math.class.getMethod("sqrt", double.class);
// print tables of x- and y-values
printTable(1, 10, 10, square);
printTable(1, 10, 10, sqrt);
}
/**
Returns the square of a number
@param x a number
@return x squared
*/
public static double square(double x)
{
return x * x;
}
/**
Prints a table with x- and y-values for a method
@param from the lower bound for the x-values
@param to the upper bound for the x-values
@param n the number of rows in the table
@param f a method with a double parameter and double return value
*/
public static void printTable(double from, double to, int n, Method f)
{
// print out the method as table header
System.out.println(f);
double dx = (to - from) / (n - 1);
for (double x = from; x <= to; x += dx)
{
try
{
double y = (Double) f.invoke(null, x);
System.out.printf("%10.4f | %10.4f%n", x, y);
}
catch (Exception e) { e.printStackTrace(); }
}
}
}
@@ -0,0 +1,82 @@
/**
@version 1.11 2004-02-21
@author Cay Horstmann
*/
import java.lang.reflect.*;
import java.util.*;
import java.text.*;
public class ObjectAnalyzerTest
{
public static void main(String[] args)
{
ArrayList<Integer> squares = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) squares.add(i * i);
System.out.println(new ObjectAnalyzer().toString(squares));
}
}
class ObjectAnalyzer
{
/**
Converts an object to a string representation that lists
all fields.
@param obj an object
@return a string with the object's class name and all
field names and values
*/
public String toString(Object obj)
{
if (obj == null) return "null";
if (visited.contains(obj)) return "...";
visited.add(obj);
Class cl = obj.getClass();
if (cl == String.class) return (String) obj;
if (cl.isArray())
{
String r = cl.getComponentType() + "[]{";
for (int i = 0; i < Array.getLength(obj); i++)
{
if (i > 0) r += ",";
Object val = Array.get(obj, i);
if (cl.getComponentType().isPrimitive()) r += val;
else r += toString(val);
}
return r + "}";
}
String r = cl.getName();
// inspect the fields of this class and all superclasses
do
{
r += "[";
Field[] fields = cl.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
// get the names and values of all fields
for (Field f : fields)
{
if (!Modifier.isStatic(f.getModifiers()))
{
if (!r.endsWith("[")) r += ",";
r += f.getName() + "=";
try
{
Class t = f.getType();
Object val = f.get(obj);
if (t.isPrimitive()) r += val;
else r += toString(val);
}
catch (Exception e) { e.printStackTrace(); }
}
}
r += "]";
cl = cl.getSuperclass();
}
while (cl != null);
return r;
}
private ArrayList<Object> visited = new ArrayList<Object>();
}
@@ -0,0 +1,98 @@
/**
@version 1.01 2004-02-21
@author Cay Horstmann
*/
import java.text.*;
import java.util.*;
public class PersonTest
{
public static void main(String[] args)
{
Person[] people = new Person[2];
// fill the people array with Student and Employee objects
people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
people[1] = new Student("Maria Morris", "computer science");
// print out names and descriptions of all Person objects
for (Person p : people)
System.out.println(p.getName() + ", " + p.getDescription());
}
}
abstract class Person
{
public Person(String n)
{
name = n;
}
public abstract String getDescription();
public String getName()
{
return name;
}
private String name;
}
class Employee extends Person
{
public Employee(String n, double s,
int year, int month, int day)
{
super(n);
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public String getDescription()
{
return String.format("an employee with a salary of $%.2f", salary);
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
private double salary;
private Date hireDay;
}
class Student extends Person
{
/**
@param n the student's name
@param m the student's major
*/
public Student(String n, String m)
{
// pass n to superclass constructor
super(n);
major = m;
}
public String getDescription()
{
return "a student majoring in " + major;
}
private String major;
}
@@ -0,0 +1,114 @@
/**
@version 1.1 2004-02-21
@author Cay Horstmann
*/
import java.util.*;
import java.lang.reflect.*;
public class ReflectionTest
{
public static void main(String[] args)
{
// read class name from command line args or user input
String name;
if (args.length > 0)
name = args[0];
else
{
Scanner in = new Scanner(System.in);
System.out.println("Enter class name (e.g. java.util.Date): ");
name = in.next();
}
try
{
// print class name and superclass name (if != Object)
Class cl = Class.forName(name);
Class supercl = cl.getSuperclass();
System.out.print("class " + name);
if (supercl != null && supercl != Object.class)
System.out.print(" extends " + supercl.getName());
System.out.print("\n{\n");
printConstructors(cl);
System.out.println();
printMethods(cl);
System.out.println();
printFields(cl);
System.out.println("}");
}
catch(ClassNotFoundException e) { e.printStackTrace(); }
System.exit(0);
}
/**
Prints all constructors of a class
@param cl a class
*/
public static void printConstructors(Class cl)
{
Constructor[] constructors = cl.getDeclaredConstructors();
for (Constructor c : constructors)
{
String name = c.getName();
System.out.print(" " + Modifier.toString(c.getModifiers()));
System.out.print(" " + name + "(");
// print parameter types
Class[] paramTypes = c.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++)
{
if (j > 0) System.out.print(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
/**
Prints all methods of a class
@param cl a class
*/
public static void printMethods(Class cl)
{
Method[] methods = cl.getDeclaredMethods();
for (Method m : methods)
{
Class retType = m.getReturnType();
String name = m.getName();
// print modifiers, return type and method name
System.out.print(" " + Modifier.toString(m.getModifiers()));
System.out.print(" " + retType.getName() + " " + name + "(");
// print parameter types
Class[] paramTypes = m.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++)
{
if (j > 0) System.out.print(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
/**
Prints all fields of a class
@param cl a class
*/
public static void printFields(Class cl)
{
Field[] fields = cl.getDeclaredFields();
for (Field f : fields)
{
Class type = f.getType();
String name = f.getName();
System.out.print(" " + Modifier.toString(f.getModifiers()));
System.out.println(" " + type.getName() + " " + name + ";");
}
}
}
@@ -0,0 +1,50 @@
/**
@version 1.10 2004-02-27
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class AnonymousInnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock();
clock.start(1000, true);
// keep program running until user selects "Ok"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
/**
A clock that prints the time in regular intervals.
*/
class TalkingClock
{
/**
Starts the clock.
@param interval the interval between messages (in milliseconds)
@param beep true if the clock should beep
*/
public void start(int interval, final boolean beep)
{
ActionListener listener = new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
};
Timer t = new Timer(interval, listener);
t.start();
}
}
@@ -0,0 +1,76 @@
/**
@version 1.10 2002-07-01
@author Cay Horstmann
*/
import java.util.*;
public class CloneTest
{
public static void main(String[] args)
{
try
{
Employee original = new Employee("John Q. Public", 50000);
original.setHireDay(2000, 1, 1);
Employee copy = original.clone();
copy.raiseSalary(10);
copy.setHireDay(2002, 12, 31);
System.out.println("original=" + original);
System.out.println("copy=" + copy);
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
class Employee implements Cloneable
{
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee clone() throws CloneNotSupportedException
{
// call Object.clone()
Employee cloned = (Employee)super.clone();
// clone mutable fields
cloned.hireDay = (Date)hireDay.clone();
return cloned;
}
/**
Set the hire day to a given date
@param year the year of the hire day
@param month the month of the hire day
@param day the day of the hire day
*/
public void setHireDay(int year, int month, int day)
{
hireDay = new GregorianCalendar(year, month - 1, day).getTime();
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString()
{
return "Employee[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
}
private String name;
private double salary;
private Date hireDay;
}
@@ -0,0 +1,69 @@
/**
@version 1.30 2004-02-27
@author Cay Horstmann
*/
import java.util.*;
public class EmployeeSortTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry Hacker", 35000);
staff[1] = new Employee("Carl Cracker", 75000);
staff[2] = new Employee("Tony Tester", 38000);
Arrays.sort(staff);
// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
}
}
class Employee implements Comparable<Employee>
{
public Employee(String n, double s)
{
name = n;
salary = s;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
/**
Compares employees by salary
@param other another Employee object
@return a negative value if this employee has a lower
salary than otherObject, 0 if the salaries are the same,
a positive value otherwise
*/
public int compareTo(Employee other)
{
if (salary < other.salary) return -1;
if (salary > other.salary) return 1;
return 0;
}
private String name;
private double salary;
}
@@ -0,0 +1,63 @@
/**
@version 1.10 2004-02-27
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class InnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock(1000, true);
clock.start();
// keep program running until user selects "Ok"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
/**
A clock that prints the time in regular intervals.
*/
class TalkingClock
{
/**
Constructs a talking clock
@param interval the interval between messages (in milliseconds)
@param beep true if the clock should beep
*/
public TalkingClock(int interval, boolean beep)
{
this.interval = interval;
this.beep = beep;
}
/**
Starts the clock.
*/
public void start()
{
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t.start();
}
private int interval;
private boolean beep;
private class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
}
Loaded 100 of 493 files, more files were not shown because too many files have changed in this diff. Show more