此Java程序依次输出参数,参数类型为字符型,要求更改程序,使得字符型强制转化为整形,并将这些整数相加,最后输出总和。
原程序:
package demo; public class CommandParameter { public static void main(String[] args){ System.out.println("参数个数:"+args.length); for(String arg:args){ System.out.println(arg);
}
} }
思路:
①先将字符型转化为整型(利用Integer.praseInt(arg))。
②用for循环,将几个数相加。
源代码:
package demo; public class CommandParameter { public static void main(String [] args){ System.out.println("参数个数:"+args.length); int sum=0; int num; for(String arg:args){ num=Integer.parseInt(arg); sum=sum+num; } System.out.println("总和是:"+sum); } }