Skip to content

Commit d073133

Browse files
committed
Method with variable input without overloading
1 parent 1785142 commit d073133

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Java/Advanced/Varargs.java

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
You are given a class Solution and its main method in the editor.
3+
Your task is to create the class Add and the required methods so that the code prints the sum of the numbers passed to the function add.
4+
5+
Note: Your add method in the Add class must print the sum as given in the Sample Output
6+
7+
Input Format
8+
There are six lines of input, each containing an integer.
9+
10+
Output Format
11+
There will be only four lines of output. Each line contains the sum of the integers passed as the parameters to add in the main method.
12+
*/
13+
14+
import java.io.BufferedReader;
15+
import java.io.InputStreamReader;
16+
import java.lang.reflect.Method;
17+
import java.util.*;
18+
class Add {
19+
public void add (int ... n) {
20+
int r = n[0];
21+
int sum = 0;
22+
for (int i = 0; i < n.length; i++) {
23+
sum += n[i];
24+
System.out.print(n[i]);
25+
if (i<n.length-1) {
26+
System.out.print("+");
27+
}
28+
}
29+
System.out.println("=" + sum);
30+
}
31+
}
32+
public class Varargs {
33+
34+
35+
public static void main(String[] args) {
36+
try{
37+
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
38+
int n1=Integer.parseInt(br.readLine());
39+
int n2=Integer.parseInt(br.readLine());
40+
int n3=Integer.parseInt(br.readLine());
41+
int n4=Integer.parseInt(br.readLine());
42+
int n5=Integer.parseInt(br.readLine());
43+
int n6=Integer.parseInt(br.readLine());
44+
Add ob=new Add();
45+
ob.add(n1,n2);
46+
ob.add(n1,n2,n3);
47+
ob.add(n1,n2,n3,n4,n5);
48+
ob.add(n1,n2,n3,n4,n5,n6);
49+
Method[] methods=Add.class.getDeclaredMethods();
50+
Set<String> set=new HashSet<>();
51+
boolean overload=false;
52+
for(int i=0;i<methods.length;i++)
53+
{
54+
if(set.contains(methods[i].getName()))
55+
{
56+
overload=true;
57+
break;
58+
}
59+
set.add(methods[i].getName());
60+
61+
}
62+
if(overload)
63+
{
64+
throw new Exception("Overloading not allowed");
65+
}
66+
}
67+
catch(Exception e)
68+
{
69+
e.printStackTrace();
70+
}
71+
}
72+
}

0 commit comments

Comments
 (0)