Java Varargs - Simple Addition

Sort by

recency

|

294 Discussions

|

  • + 0 comments

    class Add { public void add(int... x) { //int r = 0; String seperator = ""; int count = 0; int result = 0; for(int a : x) { //System.out.println(count+a); count = count + a; //System.out.println(a); System.out.print(seperator +a); seperator = "+";

       }
       result = count;
       System.out.print("="+result);
       System.out.println();
    

    } }

  • + 0 comments

    class Add{
    public void add(int... a){ int sum = 0; int plus = a.length-1; for(int x:a){ sum += x; System.out.print(x);
    if(plus>0){ System.out.print("+"); plus--; }
    } System.out.print("="+sum); System.out.println(); } }

  • + 0 comments
    class Add{
        public void add(int ... is){
            int counter = 0;
            int sum = 0;
            for (int i : is) {
                counter++;
                sum += i;
                System.out.print(i);
                if(counter == is.length){
                    System.out.print("=");
                }else{
                    System.out.print("+");
                }        
            }
            System.out.println(sum);
            
        }
    }
    
  • + 0 comments

    class Add{

        public void add(int... arr){
        int sum = arr[0];
        System.out.print(arr[0]);
        for(int i=1;i<arr.length-1;i++){
    
        System.out.print("+"+(arr[i]));
          sum=sum+arr[i];
        }
        sum=sum+arr[arr.length-1];
        System.out.print("+"+arr[arr.length-1]+"="+sum);
        System.out.println();
    }
    

    }

  • + 0 comments
    import java.util.stream.IntStream;
    class Add {
        public Add() {}
        public void add(int... nbr) {
            StringJoiner explication = new StringJoiner("+");
            for (int number : nbr) explication.add(String.valueOf(number));
            int sum = IntStream.of(nbr).sum();
            System.out.println(explication + "=" + sum);
        }
    }