我想使用命令行參數來獲取用戶輸入,並使用增強for循環來求和。java中的CommandLine參數幫助
這是錯誤:
在線程異常「主要」 java.lang.Error的:未解決的問題,編譯: 類型不匹配:不能從雙轉換爲int
public class EnhanceForLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
if(args.length !=5)
System.out.println(" please enter no more than 4 numbers");
else
{
double sum;
double arrayLength = Double.parseDouble(args[0]);
double [] myArray = new double [ arrayLength ];
double value = Double.parseDouble((args[1]));
double counter = Double.parseDouble((args[2]));
for(double num: myArray)
sum += num;
System.out.printf("The sum is %f ", sum);
}
}
}
這裏是怎麼回事是迄今爲止:
公共類EnhanceForLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
if(args.length !=5)
System.out.println(" please enter no more than 4 numbers");
else
{
double sum = 0.0;
int arrayLength = Integer.parseInt(args[0]);
double [] myArray = new double [ arrayLength ];
double num1 = Double.parseDouble((args[1]));
double num2 = Double.parseDouble((args[2]));
double num3 = Double.parseDouble((args[3]));
double num4 = Double.parseDouble((args[4]));
double num5 = Double.parseDouble((args[5]));
for(double num: myArray)
sum += num;
System.out.printf("The sum is %f ", sum);
}
}
}
下面是答案:
公共類EnhanceForLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
if(args.length !=5)
System.out.println(" please enter no more than 4 numbers");
else
{
double sum = 0.0;
int arrayLength = Integer.parseInt(args[0]);
double [] myArray = new double [ arrayLength ];
double num1 = Double.parseDouble((args[1]));
double num2 = Double.parseDouble((args[2]));
double num3 = Double.parseDouble((args[3]));
double num4 = Double.parseDouble((args[4]));
for(String s: args){
sum += Double.parseDouble(s);
}
System.out.println("Sum: "+sum);
}
}
}
除非arrayLength是一個整數,否則不能用'new double [arrayLength]'創建一個數組。 – 2011-02-23 23:00:32
所以,現在你可以從你的解決方案中刪除多餘的代碼,除了循環和其後的'System.out.println'之外的其他東西。 – 2011-02-24 01:32:49