Home > Mobile >  How can I accept any amount of Arguments in Java as Int, to for example add the numbers?
How can I accept any amount of Arguments in Java as Int, to for example add the numbers?

Time:10-19

I am trying to write a Java code where you can put any amount of numbers when running the code and it will add them all together. I know that with Integer.parseInt(args[0]); I can take 1 int but what if I want to accept as many as the user inputs?

CodePudding user response:

Summing the args, if an argument is not an "int" the program replace it with 0:

import java.util.Arrays;

public class SumArgs {
    public static void main(String[] args) {
        int result = Arrays.stream(args).mapToInt(element -> {
            try {
                return Integer.parseInt(element);
            } catch (NumberFormatException e) {
                return 0;
            }
        }).sum();
        System.out.println(result);
    }
}

CodePudding user response:

  public static void method1(int ... a ){
        for(int num: a){
            System.out.println("num = "   num);
        }
    }
  •  Tags:  
  • java
  • Related