Nikita99
Nikita99

Reputation: 55

Can someone tell me what is happening in this code (Java)?

Good afternoon,

I am a student and I want to know if I'm understanding how this code works. I think the program accepts at least two arguments that must be whole numbers and will return a new string after being executed. If the value of the total of these arguments is '0', it will show the message as the number of arguments is not valid, since no action could have been taken. However, if the arguments are different numbers from '0', the 'parseDouble' method will return twice the value of the first argument (argument 0) and the total of the following arguments will be found through the 'for' loop. Next, the 'parseDouble' method again finds twice the total arguments calculated in the loop and the operator '* =' multiplies this double by double the first argument. With the 'Math.pow' method, the value of the first argument raised to the power of the second is returned. In this case, double the first argument raised to the division of the total arguments by 1.0. (I don't know what 'str.append(result+"\n");' means)! If you try to write a word, the program will detect it and return an error message again since only whole numbers are accepted. Finally, the final result will be printed being the only one visible on a console. Is this right?


    public static void main(String[] args){
        double result = 0;      
        int  i= 0, length = args.length;
        StringBuilder str = new StringBuilder();

        if(length==0){
            System.err.println("Number of arguments is not correct! \nWrite: java Ex1 <double>+");
        }else{
            try {
                result = Double.parseDouble(args[0]);

                for (i = 1; i < length; i++) {
                    result *= Double.parseDouble(args[i]); 
                }
                result = Math.pow(result, 1.0 / length); 
                str.append(result+"\n");



            } catch (NumberFormatException e) {
                    System.err.println("Argument <<" + args[i] + ">> must be a double!");
                    System.exit(1);
            }
            System.out.print(str.toString());

        }
    }   
}```

Upvotes: 0

Views: 86

Answers (1)

Alex Sveshnikov
Alex Sveshnikov

Reputation: 4329

This code calculates the geometric mean of command line arguments: https://en.m.wikipedia.org/wiki/Geometric_mean

Upvotes: 1

Related Questions