00001
00002
00003
00004
00005 import java.io.*;
00006 import OpenList;
00007 import Quantity;
00008 import UnicalcParser;
00009 import LineBufferInputStream;
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 class Unicalc
00022 {
00023
00024
00025 static String defaultDBfilename = "/cs/cs60/bin/unicalc.db";
00026
00027
00028
00029
00030 static String promptString1 = "convert from: ";
00031
00032
00033
00034
00035 static String promptString2 = "convert to: ";
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046 OpenList DB;
00047
00048
00049
00050
00051
00052
00053
00054
00055 void readDB(String DBfilename)
00056 {
00057 DB = OpenList.nil;
00058
00059 FileInputStream filein = null;
00060
00061 try
00062 {
00063 filein = new FileInputStream(DBfilename);
00064 }
00065 catch( FileNotFoundException e )
00066 {
00067 System.out.println("*** Database file " + DBfilename + " not found.");
00068 System.exit(1);
00069 }
00070
00071 LineBufferInputStream in = new LineBufferInputStream(filein);
00072
00073 while( !in.eof() )
00074 {
00075 String LHS = in.getString();
00076
00077 String line = in.getNonBlankLine();
00078
00079 Object input = new UnicalcParser(line).parse();
00080
00081 Quantity RHS = Quantity.makeQuantity(input);
00082
00083 DB = OpenList.cons(OpenList.list(LHS, RHS), DB);
00084 }
00085 }
00086
00087
00088
00089
00090
00091
00092 static Quantity getQuantity(LineBufferInputStream in, PrintStream out)
00093 {
00094
00095
00096 Object input;
00097
00098 do
00099 {
00100 String line = in.getNonBlankLine();
00101 input = new UnicalcParser(line).parse();
00102 if( input == null )
00103 {
00104 out.println("Invalid input, please try again");
00105 }
00106 }
00107 while( input == null );
00108
00109 return Quantity.makeQuantity(input);
00110 }
00111
00112
00113
00114
00115
00116
00117
00118
00119
00120
00121 void loop(InputStream inStream, PrintStream out)
00122 {
00123 LineBufferInputStream in = new LineBufferInputStream(inStream);
00124
00125 while( true )
00126 {
00127 prompt(promptString1, out);
00128 if( in.eof() ) break;
00129
00130 Quantity fromQuantity = getQuantity(in, out);
00131
00132 prompt(promptString2, out);
00133 if( in.eof() ) break;
00134
00135 Quantity toQuantity = getQuantity(in, out);
00136
00137 Quantity conversion =
00138 Quantity.convert(fromQuantity, toQuantity, DB);
00139
00140 out.println("multiply by: " + conversion);
00141 out.println("or divide by: " + Quantity.invert(conversion));
00142 out.println();
00143 }
00144 out.println();
00145 }
00146
00147
00148
00149
00150
00151
00152 static void prompt(String promptString, PrintStream out)
00153 {
00154 out.print(promptString);
00155 out.flush();
00156 }
00157
00158
00159
00160
00161
00162
00163 static public void main(String arg[])
00164 {
00165 String DBfilename = defaultDBfilename;
00166
00167 Unicalc unicalc = new Unicalc();
00168
00169 unicalc.readDB(DBfilename);
00170
00171 unicalc.loop(System.in, System.out);
00172 }
00173
00174 }