I want to give out only one Argument instead of all 4

Viewed 67

I want that the user can type four arguments, and this results that the numbers which the user typed in get summed up together. But now I have the Problem, if the user wants to give out less arguments. How do I sum up that?

public class Sum {

    public static void main(String[] args) {
        int  q = Integer.parseInt(args[0]);
        int  w = Integer.parseInt(args[1]);
        int  e = Integer.parseInt(args[2]);
        int  r = Integer.parseInt(args[3]);

        int summe = q + w + e + r; 
        System.out.println(summe);
1 Answers

You have to check the number of input arguments (i.e. args.length) in order not to try accessing invalid indices of the args arrays.

You don't need all of these variables if you only want to compute the sum:

public static void main(String[] args) {
    int sum = 0;
    for (int i = 0; i < args.length; i++) {
         sum += Integer.parseInt (args[i]);
    }
    System.out.println(sum);
}
Related