command line arguments

PHOTO EMBED

Sat Jul 06 2024 05:58:44 GMT+0000 (Coordinated Universal Time)

Saved by @projectrock

public class CommandLineSum {
    public static void main(String[] args) {
        int sum = 0;

        // Check if there are command line arguments
        if (args.length == 0) {
            System.out.println("No command line arguments found.");
            return;
        }

        // Iterate through the command line arguments
        for (String arg : args) {
            try {
                // Convert argument to integer and add to sum
                int num = Integer.parseInt(arg);
                sum += num;
            } catch (NumberFormatException e) {
                System.out.println(arg + " is not a valid integer.");
            }
        }

        // Print the sum of integers
        System.out.println("Sum of integers: " + sum);
    }
}
content_copyCOPY