学以致用——Java源码——命令行参数的用法示例(任意个数字连乘)(Command-Line Arguments)

参考文章:

1. 命令行中执行带参数的java程序(Command-Line Arguments),https://blog.csdn.net/hpdlzu80100/article/details/51851440 

2. 学以致用——Java源码——使用变长参数列表实现n个数的连乘(Variable-Length Argument List),https://blog.csdn.net/hpdlzu80100/article/details/85248287

 

代码如下:

	//JHTP Exercise 7.14: Command-Line Arguments
	//by [email protected]
	/**7.15 (Command-Line Arguments) Rewrite Fig. 7.2 so that the size of the array is specified by the first command-line argument. If no command-line argument is supplied, use 10 as the default size of the array.*/
	 
	public class CommandLineArgumentsCmd
	{
		public static double multiply(double... factors){  //Using variable-length argument lists.
			double result=1.0;
			for (double f:factors)
				result*=f;
			return result;
		}
		
		public static void main(String[] args)
		
	{
			if (args.length < 2)
		         System.out.printf("请输入至少两个数字作为参数!%n");
		      else {
				 double[] factors = new double[args.length];
			
				 
		    	 for (int i=0; i

运行过程及结果:

D:\Java\eclipseWorkspace\jhtp2018\pd\src\main\java\exercises\ch7Arrays>javac -encoding utf-8 CommandLineArgumentsCmd.java
D:\Java\eclipseWorkspace\jhtp2018\pd\src\main\java\exercises\ch7Arrays>java CommandLineArgumentsCmd
请输入至少两个数字作为参数!
D:\Java\eclipseWorkspace\jhtp2018\pd\src\main\java\exercises\ch7Arrays>java CommandLineArgumentsCmd 2018
请输入至少两个数字作为参数!
D:\Java\eclipseWorkspace\jhtp2018\pd\src\main\java\exercises\ch7Arrays>java CommandLineArgumentsCmd 20.18 20.19
20.18 × 20.19 = 407.43

 

你可能感兴趣的:(Java编程(Java,Programming))