Section 4.8. Command Line Input

   

4.8 Command Line Input

Generally, arguments are sent to programs run on the command line by simply typing them after the name of the program you're about to run. The program will likely expect them in a certain order. For instance, think of modifying the DebtApp program to accept debt, expenses, and income values: the program will expect the values in a certain order. We could modify the program to accept first income, then expenses, then debt. Instead of hardcoding these values inside the program, which requires you to retype inside the code (which could be dangerous), and then recompile the program (which takes time), you could pass them in as arguments. Here is how we had it written inside the DebtApp class:

 ...          // initialize vars         income = 115000;         expenses = 82000;         debt = 149000; ... 

Now at first glance, it might seem okay to write the following:

 // initialize vars  income = args[0]; expenses = args[1]; debt = args[2];    // won't work! 

That's because Java needs int s for each of those values, and although we are correctly referencing the cells in the args array, these are strings. So we have to parse them; this should do the trick:

 // convert Strings to ints  income = Integer.parseInt(args[0]); expenses = Integer.parseInt(args[1]); debt = Integer.parseInt(args[2]); 

Then recompile the program and call it, supplying values for each of the three arguments, like this:

 C:\jdk1.4\JavaForCF\chp4>java DebtApp 115000 117000 105000  You are living the life... But your debt will never be paid off. 

The program runs and prints the output. But now you can call it again with different values, and you don't have to recompile.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net