We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
class Add {
public void add(int... numbers) {
int sum = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
sb.append(numbers[i]);
if (i != numbers.length - 1) {
sb.append("+");
}
}
sb.append("=").append(sum);
System.out.println(sb);
}
}
public class Solution {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int n3 = sc.nextInt();
int n4 = sc.nextInt();
int n5 = sc.nextInt();
int n6 = sc.nextInt();
Add ob = new Add();
ob.add(n1, n2);
ob.add(n1, n2, n3);
ob.add(n1, n2, n3, n4, n5);
ob.add(n1, n2, n3, n4, n5, n6);
// Reflection check (required by HackerRank)
Method[] methods = Add.class.getDeclaredMethods();
Set<String> set = new HashSet<>();
boolean overload = false;
for (Method method : methods) {
if (set.contains(method.getName())) {
overload = true;
break;
}
set.add(method.getName());
}
if (overload) {
throw new Exception("Overloading not allowed");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Varargs - Simple Addition
You are viewing a single comment's thread. Return to all comments →
java15:
import java.io.; import java.lang.reflect.; import java.util.*;
class Add { public void add(int... numbers) { int sum = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < numbers.length; i++) { sum += numbers[i]; sb.append(numbers[i]); if (i != numbers.length - 1) { sb.append("+"); } } sb.append("=").append(sum); System.out.println(sb); } }
public class Solution { public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); int n1 = sc.nextInt(); int n2 = sc.nextInt(); int n3 = sc.nextInt(); int n4 = sc.nextInt(); int n5 = sc.nextInt(); int n6 = sc.nextInt(); Add ob = new Add(); ob.add(n1, n2); ob.add(n1, n2, n3); ob.add(n1, n2, n3, n4, n5); ob.add(n1, n2, n3, n4, n5, n6);
}