About Lesson
Command-line arguments are passed as strings, so you need to parse and convert them to the appropriate data types within the application.
If an argument contains spaces or special characters, it should be enclosed in double quotes ("
).
public class CommandLineArgumentsSum {
public static void main(String[] args) {
// Check if command-line arguments are provided
if (args.length == 0) {
System.out.println("No command-line arguments provided.");
} else {
int sum = 0;
// Iterate through each command-line argument
for (String arg : args) {
// Convert each argument to an integer and add to the sum
try {
int num = Integer.parseInt(arg);
sum += num;
} catch (NumberFormatException e) {
System.err.println("Invalid integer format: " + arg);
return; // Exit the program if an invalid argument is encountered
}
}
// Print the sum of command-line arguments
System.out.println("Sum of command-line arguments: " + sum);
}
}
}