学以致用——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 pandenghuang@163.com
	/**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<args.length;i++) {
		    		 if (i<args.length-1) {
		    			 factors[i] = Double.parseDouble(args[i]);
		    			 System.out.printf("%.2f × ", factors[i]); 
		    		 }
		    		 else{
		    			 factors[i] = Double.parseDouble(args[i]);
		    			 System.out.printf("%.2f = ",factors[i]); 
		    	 }		 
		    	 }
		    	 
		    	 System.out.printf("%.2f",multiply(factors)); 	
		      }
	}
	}

运行过程及结果:

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值