AvenNova AvenNova - 5 months ago 18
Java Question

Getting an error running this program as a command line argument in Java, how can I fix this?

I am getting an error when I try to run this program as a command line argument in Eclipse. This is what the error says:

Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

When I change the main method to String then I can't call on the second method as the String main method is not compatible with the int returnSum method.

I need to have the returnSums method be a int type method as per the requirements but I can't figure out how to do this without getting an error. It says in the requirements that i need to use variable number of arguments for the method but have a hard time grasping the idea.

Can someone please help me with this? Here's my code:

public static void main(int[] args) {

// Printing the entered digits
System.out.print("Passing");
System.out.print(" [ ");

for (int nums = 0; nums < args.length; nums++) {
System.out.print(args[nums] + " ");

}
System.out.print("] ");
System.out.println("\nSum is " + returnSum(args)); // Calling on the second method for the sum

}
// Taking the nums from the main method as arguments
public static int returnSum(int...args) {
int sum = 0;
// Calculating the sum
for (int nums = 0; nums < args.length; nums++) {
sum = sum + nums;
}
return sum;

}

Answer

Try Below Code:

public class SumOfNumbers {
    public static void main(String[] args) {

        int[] intArgs = new int[args.length];
        for (int x = 0; x < args.length; x++) {
            if (args[x].matches("\\d+")) {
                intArgs[x] = Integer.parseInt(args[x]);
            } else {
                System.out.println(args[x] + " is not a Integer hence skiped in this program");
            }
        }

        // Printing the entered digits
        System.out.print("Passing");
        System.out.print(" [ ");

        for (int nums = 0; nums < intArgs.length; nums++) {
            System.out.print(intArgs[nums] + " ");

        }
        System.out.print("] ");
        System.out.println("\nSum is " + returnSum(intArgs)); // Calling on the second method for the sum

    }

    // Taking the nums from the main method as arguments
    public static int returnSum(int... args) {
        int sum = 0;
        // Calculating the sum
        for (int nums = 0; nums < args.length; nums++) {
            sum = sum + args[nums];
        }
        return sum;
    }
}