home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Java 1.2 How-To
/
JavaHowTo.iso
/
code
/
ch02.txt
next >
Wrap
Text File
|
1998-12-14
|
20KB
|
783 lines
Convert.java:
/*
Convert.class prints a short table of common conversion factors.
*/
class Convert {
/*
* Note that the main method must be defined as
* public static void main (String []) to be called from
* the Java interpreter.
*/
public static void main (String args[]) {
double mi_to_km = 1.609;
double gals_to_l = 3.79;
double kg_to_lbs = 2.2;
System.out.print ("1 Mile equals\t");
System.out.print (mi_to_km);
System.out.println ("\tKilometers");
System.out.print ("1 Gallon equals\t");
System.out.print (gals_to_l);
System.out.print ("\tLiters\n");
System.out.print ("1 Kilogram equals\t");
System.out.print (kg_to_lbs);
System.out.println ("\tPounds");
}
}
Input.java:
import java.io.*;
/*
* Input.class reads a line of text from standard input,
* determines the length of the line, and prints it.
*/
class Input {
public static void main (String args[]) {
String input = "";
boolean error;
/*
* BufferedReader contains the readLine method.
* Create a new instance for standard input System.in
*/
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
/*
* This loop is used to catch I/O exceptions that may occur
*/
do {
error = false;
System.out.print ("Enter the string > ");
/*
* We need to flush the output - no newline at the end
*/
System.out.flush ();
try {
input = in.readLine ();
} catch (IOException e) {
System.out.println (e);
System.out.println ("An input error was caught");
error = true;
}
} while (error);
System.out.print ("You entered \"");
System.out.print (input); /
System.out.println ("\"");
System.out.print ("The length is ");
System.out.println (input.length ());
} // end of main ()
Tip.java:
import java.io.*;
/*
* Tip.class calculates the tip, given the bill and tip percentage
*/
class Tip {
public static void main (String args[]) {
String input = "";
int tip_percent=0;
double bill=0, tip=0;
boolean error;
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
do {
error = false;
System.out.print ("Enter the bill total > ");
System.out.flush ();
try {
input = in.readLine ();
} catch (IOException e) {
System.out.println (e);
System.exit (1);
}
/*
* Convert input string to double,
*/
try {
bill = Double.valueOf (input).doubleValue();
} catch (NumberFormatException e) {
System.out.println (e);
System.out.println ("Please try again");
error = true;
}
} while (error);
do {
error = false;
System.out.print ("Enter the tip amount in percent > ");
System.out.flush ();
try {
input = in.readLine ();
} catch (IOException e) {
System.out.println (e);
System.exit (1);
}
/*
* This time convert to Integer
*/
try {
tip_percent = Integer.valueOf (input).intValue();
} catch (NumberFormatException e) {
System.out.println (e);
System.out.println ("Please try again");
error = true;
}
} while (error);
System.out.print ("The total is ");
tip = bill * ((double) tip_percent)/100.0;
System.out.println (bill + tip);
} // end of main ()
}
BigNum.java:
/*
* BigNum.class converts a very large number to a string
* and then prints it out
*/
class BigNum {
public static void main (String args[]) {
/*
* Good thing longs are 64 bits!
*/
long debt = 3965170506502L;
long pop = 250410000;
print ("The 1992 national debt was $", debt);
print ("The 1992 population was ", pop);
print ("Each person owed $", debt/pop);
}
/*
* print method converts a long to a string with commas
* for easy reading. We need it with these big numbers!
* String str preceding label
* long n the long to format and print
*/
public static void print (String str,long n) {
System.out.print (str); // print the label
String buf = String.valueOf (n); // Integer to String
int start, end, ncommas, i;
int buflen = buf.length ();
/*
* It's a crazy algorithm, It works from left to right
*/
ncommas = buflen/3;
if (ncommas * 3 == buflen) ncommas -= 1;
start = 0;
end = buflen-(3*ncommas);
System.out.print (buf.substring (start, end));
for (i=0; i<ncommas; i+=1) {
start = end;
end = start+3;
System.out.print (",");
System.out.print (buf.substring (start, end));
}
System.out.println (""); // The final newline
}
}
Parms.java:
/* Parms.class prints the month and year, which are passed in
* as command-line arguments
*/
class Parms {
public static void main (String args[]) {
/*
* Java, unlike C/C++, does not need argument count (argc)
*/
if (args.length < 2) {
System.out.println ("usage: java Parms <month> <year>");
System.exit (1);
}
/*
* Unlike in C/C++, args[0] is the FIRST argument.
* The application name is not available as an argument
*/
int month = Integer.valueOf (args[0]).intValue();
int year = Integer.valueOf (args[1]).intValue();
if (month < 1 || month > 12) {
System.out.println ("Month must be between 1 and 12");
System.exit (1);
}
if (year < 1970) {
System.out.println ("Year must be greater than 1969");
System.exit (1);
}
System.out.print ("The month that you entered is ");
System.out.println (month);
System.out.print ("The year that you entered is ");
System.out.println (year);
}
}
More.java:
import java.io.*;
/*
* More.class similar to UNIX more utility
*/
class More {
public static void main (String args[])
{
String buf;
FileInputStream fs=null;
int nlines;
if (args.length != 1) {
System.out.println ("usage: java More <file>");
System.exit (1);
}
/*
* Try to open the filename specified by args[0]
*/
try {
fs = new FileInputStream (args[0]);
} catch (Exception e) {
System.out.println (e);
System.exit (1);
}
/*
* Create a BufferedReader associated with FileInputStream fs
*
*/
BufferedReader ds = new BufferedReader(new InputStreamReader(fs));
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
nlines = 0;
while (true) {
try {
buf = ds.readLine (); // read 1 line
if (buf == null) break;
} catch (IOException e) {
System.out.println (e);
break;
}
System.out.println (buf);
nlines += 1;
if (nlines % 23 == 0) { // 23 lines/pages vt100
System.out.print ("-More-");
System.out.flush ();
try {
keyboard.readLine ();
} catch (IOException e) {
}
}
}
/*
* close can throw an exception also,
* and catch it for completeness
*/
try {
fs.close ();
} catch (IOException e) {
System.out.println (e);
}
}
}
Format.java:
import java.io.*;
/*
Format.class translates a text file
* to either DOS, Mac, or UNIX
* format. The differences are in line termination.
*/
class Format {
static final int TO_DOS = 1;
static final int TO_MAC = 2;
static final int TO_UNIX = 3;
static final int TO_UNKNOWN = 0;
static void usage () {
System.out.print ("usage: java Format -dmu <in-file> ");
System.out.println ("<out-file>");
System.out.println ("\t-d converts <in-file> to DOS");
System.out.println ("\t-m converts <in-file> to MAC");
System.out.println ("\t-u converts <in-file> to UNIX");
}
public static void main (String args[])
{
int format=TO_UNKNOWN;
String buf;
FileInputStream fsIn = null;
FileOutputStream fsOut = null;
if (args.length != 3) { // you must specify format, in, out
usage ();
System.exit (1);
}
/*
args[0] is a String, so we can use
* the equals (String) method for
* comparisons
*/
if (args[0].equals ("-d")) format = TO_DOS; else
if (args[0].equals ("-m")) format = TO_MAC; else
if (args[0].equals ("-u")) format = TO_UNIX; else {
usage ();
System.exit (1);
}
try {
fsIn = new FileInputStream (args[1]);
} catch (Exception e) {
System.out.println (e);
System.exit (1);
}
/*
* FileOutputStream is the complement of FileInputStream
*/
try {
fsOut = new FileOutputStream (args[2]);
} catch (Exception e) {
System.out.println (e);
System.exit (1);
}
BufferedReader dsIn = new BufferedReader(new InputStreamReader(fsIn));
PrintStream psOut = new PrintStream (fsOut);
while (true) {
try {
buf = dsIn.readLine ();
if (buf == null) break; // break on EOF
} catch (IOException e) {
System.out.println (e);
break;
}
psOut.print (buf);
switch (format) {
case TO_DOS:
psOut.print ("\r\n");
break;
case TO_MAC:
psOut.print ("\r");
break;
case TO_UNIX:
psOut.print ("\n");
break;
}
}
/*
*/
try {
fsIn.close ();
fsOut.close ();
} catch (IOException e) {
System.out.println (e);
}
}
}
Stringcat.java:
import java.io.*;
/*
* Stringcat.class prints integers and strings together.
*/
class Stringcat {
public static void main (String args[]) {
String today = "";
int monthday = 15;
/* The string "Today is " and date are concatenated together and
* assigned to the String today.
*/
today = "Today is the " + monthday + "th";
/* The String today is printed with println
*/
System.out.println (today);
/* Here two text strings are concatenated with the integer
monthday within the println method.
*/
System.out.println ("Today is the " + monthday +
" day of the month");
} // end of main ()
}
Sort.java:
import java.io.*;
/*
* Sort.class reads a text file specified by args[0] and
* sorts each line for display
*/
class Sort {
static final int NMaxLines = 128; // an arbitrary limit
public static void main (String args[]) {
/*
* Allocate new array of strings; this is where the file
* is read and sorted in place
*/
String sortArray[] = new String [NMaxLines];
FileInputStream fs=null;
int nlines;
if (args.length != 1) {
System.out.println ("usage: java Sort <file>");
System.exit (1);
}
try {
fs = new FileInputStream (args[0]);
} catch (Exception e) {
System.out.println ("Unable to open "+args[0]);
System.exit (1);
}
BufferedReader ds = new BufferedReader(new InputStreamReader(fs));
for (nlines=0; nlines<NMaxLines; nlines += 1) {
try {
sortArray[nlines] = ds.readLine ();
if (sortArray[nlines] == null) break;
} catch (IOException e) {
System.out.println("Exception caught during read.");
break;
}
}
try {
fs.close ();
} catch (IOException e) {
System.out.println ("Exception caught closing file.");
}
/*
* Sort in place and print
*/
QSort qsort = new QSort ();
qsort.sort (sortArray, nlines);
print (sortArray, nlines);
}
/*
* print method prints an array of strings of n elements
* String a[] array of strings to print
* int n number of elements
*/
private static void print (String a[], int n) {
int i;
for (i=0; i<n; i+=1) System.out.println (a[i]);
System.out.println ("");
}
}
/*
* QSort.class uses the standard quicksort algorithm
* Detailed explanation of the techniques are found in online help
*/
class QSort {
/*
* This is used internally, so make it private
*/
private void sort (String a[], int lo0, int hi0) {
int lo = lo0;
int hi = hi0;
if (lo >= hi) return;
String mid = a[(lo + hi) / 2];
while (lo < hi) {
while (lo<hi && a[lo].compareTo (mid) < 0) lo += 1;
while (lo<hi && a[hi].compareTo (mid) > 0) hi -= 1;
if (lo < hi) {
String T = a[lo];
a[lo] = a[hi];
a[hi] = T;
}
}
if (hi < lo) {
int T = hi;
hi = lo;
lo = T;
}
sort(a, lo0, lo); // Yes, it is recursive
sort(a, lo == lo0 ? lo+1 : lo, hi0);
}
/*
* The method called to start the sort
* String a[] an array of strings to be sorted in place
* int n the number of elements in the array
*/
public void sort (String a[], int n) {
sort (a, 0, n-1);
}
}
Phone.java:
import java.io.*;
import java.util.StringTokenizer;
/*
* Phone.class implements a simple phone book with fuzzy
* name lookup. The phone book file could be created with a
* text editor or a spreadsheet saved as tab-delimited text.
*/
class Phone {
public static void main (String args[])
{
String buf;
FileInputStream fs=null;
if (args.length != 1) {
System.out.println ("usage: java Phone <name>");
System.exit (1);
}
/*
* PhoneBook.txt is the name of the phone book file.
*/
try {
fs = new FileInputStream ("PhoneBook.txt");
} catch (Exception e) {
System.out.println ("Unable to open PhoneBook.txt");
System.exit (1);
}
BufferedReader ds = new BufferedReader(new InputStreamReader(fs));
while (true) {
try {
buf = ds.readLine ();
if (buf == null) break;
} catch (IOException e) {
System.out.println ("Exception caught reading file.");
break;
}
/*
* Create a new StringTokenizer for each line read
* Explicitly specify the delimiters as both colons and tabs
*/
StringTokenizer st = new StringTokenizer(buf, ":\t");
String name = st.nextToken ();
if (contains (name, args[0])) {
System.out.println (name);
System.out.println (st.nextToken ());
System.out.println (st.nextToken () + "\n");
}
}
try {
fs.close ();
} catch (IOException e) {
System.out.println ("Exception caught closing file.");
}
}
/*
* contains method is a fuzzy string compare that returns true
* if either string is completely contained in the other one
* String s1, s2 two strings to compare
*/
static boolean contains (String s1, String s2) {
int i;
int l1 = s1.length ();
int l2 = s2.length ();
if (l1 < l2) {
for (i=0; i<=l2-l1; i+=1)
if (s1.regionMatches (true, 0, s2, i, l1))
return true;
}
for (i=0; i<=l1-l2; i+=1)
if (s2.regionMatches (true, 0, s1, i, l2))
return true;
return false;
}
}
Ammortize.java:
import java.io.*;
/*
* Ammortize.class calculates monthly payment given
* loan amount, interest, and the number of years of the loan
*/
class Ammortize {
public static void main (String args[]) {
double loanAmount=0, interest=0, years=0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
loanAmount = inputDouble ("Enter the loan amount in dollars > ", in);
interest = inputDouble ("Enter the interest rate in percent > ", in);
years = inputDouble ("Enter the number of years > ", in);
System.out.print ("The payment is $");
System.out.println (payment (loanAmount, interest, years));
} // end of main ()
/*
* inputDouble method prints a prompt and reads a double
* BufferedReader
*/
static double inputDouble (String prompt, BufferedReader in) {
boolean error;
String input="";
double value=0;
do {
error = false;
System.out.print (prompt);
System.out.flush ();
try {
input = in.readLine ();
} catch (IOException e) {
System.out.println ("An input error was caught");
System.exit (1);
}
try {
value = Double.valueOf (input).doubleValue();
} catch (NumberFormatException e) {
System.out.println ("Please try again");
error = true;
}
} while (error);
return value;
} // end of inputDouble ()
/*
* payment method does the magic calculation
* double A loan amount
* double I interest rate, as a percentage
* double Y number of years
*/
static double payment (double A, double I, double Y) {
/*
* call the exponentiation and natural log functions as
* static methods in the Math class
*/
double top = A * I / 1200;
double bot = 1 - Math.exp (Y*(-12) * Math.log (1 + I/1200));
return top / bot;
} // end of payment ()
}