Java Reference
In-Depth Information
After compiling this code, let us execute the bytecode using java as follows:
prompt%java ParsingMain Once upon a time there was a programming language
named Java!
0:Once
1:upon
2:a
3:time
4:there
5:was
6:a
7:programming
8:language
9:named
10:Java!
We can use the string array passed as argument of the main function of
programs, to process inputs. Since these elementary inputs are considered as
strings, we may eventually need to re-interpret them into the appropriate type
before processing them. For example, consider the following program that seeks
for the smallest integer entered in the arguments of the command line:
Program 4.14 Array of strings in main
class ParseArgumentsMin {
public static void main( String [ ]
args )
{ int indexMin=0;
for ( int i=1; i < args . length ; i++)
if
(Integer . parseInt(args [indexMin ]) > Integer . parseInt(
args [ i ]) )
indexMin=i ;
System . out . println ( "Maximum argument found at index:" +
indexMin+ ":" +args [ indexMin ]) ;
}
}
Compiling and running this program with argument strings “345”, “546”,
“234”, “2” and “45”, we get:
prompt%javac ParseArgumentsMinInt.java
prompt%java ParseArgumentsMin 345 546 234 2 45
Maximum argument found at index:3 :2
Once the strings are converted into corresponding integers using the library
function Integer.parseInt , we get the index of the smallest argument: 2.
Indeed args[3] corresponds to the string “2.”
 
Search WWH ::




Custom Search