简体   繁体   中英

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

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?

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);
    }
}
  public static void method1(int ... a ){
        for(int num: a){
            System.out.println("num = " + num);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM