Command line arguments in java help

I suggest using command line arguments to enter user input, and also use an extended loop to summarize.

This is mistake:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Mismatch type: cannot be converted from double to 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);

    }

}

}

this is how it is so far:

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 = 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);

    }

}

}


Here is the answer:

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 = 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);
    }




}

}


+3
source share
3 answers

You are summing up an array populated 0.0(since this is the default), not command line arguments.

, (= args), double . double[].


: ( )

, , , , . , args myArray. Integer.parseInt(...) Double.parseDouble , sum.

, { ... } .

+2

arrayLength . ,

int arrayLength = Integer.parseInt(args[0]);
double [] myArray = new double [ arrayLength ];
+4

:

. .

, .

+3

Source: https://habr.com/ru/post/1794278/


All Articles