Java Reference
In-Depth Information
prompt gcd 120 28
These numbers are in fact plain sequences of characters that are stored in
Java strings. Thus the program needs at first to reinterpret these strings
into appropriate numbers (integers or reals), prior to assigning them to
variables. To parse a string and get its equivalent integer ( int ), one uses
Integer.parseInt(stringname); . For reals, to parse and create the cor-
responding float or double from a given string str , use the following
functions: Float.parseFloat(str) or Double.parseDouble(str) . Let us
revisit Euclid's GCD program by taking the two numbers a and b from the
program arguments:
class gcd {
public static void main( String [ ] arg )
// Parse arguments into integer parameters
int a= Integer . parseInt(arg [0]) ;
int b= Integer . parseInt(arg [1]) ;
System . out . println ( "Computing GCD(" +a+ "," +b+ ")" );
while (a!=b)
if (a > b) a=a
b;
a;
// Display to console
System . out . println ( "Greatest common divisor is " +a ) ;
}
}
else b=b
Compiling and running this program yields:
prompt%java gcd 234652 3456222
Computing GCD(234652,3456222)
Greatest common divisor is 22
But there is more. In Chapter 1.8, we explained the basic mechanism of
input/output redirections (I/O redirections). Using I/O redirections with
program arguments yields an ecient framework for executing and testing
programs. Let us export the result to a text file named result.txt :
prompt%java gcd 234652 3456222 >result.txt
Then we saved the texts previously written on the console to that file. We can
visualize its contents as follows:
prompt%more result.txt
Computing GCD(234652,3456222)
Greatest common divisor is 22
We are now ready to proceed to the next chapter concentrating on functions
and procedures.
Search WWH ::




Custom Search