TASK 5. Methods Overloading. Review Methods, Implement the following code, test it with different input, make sure it runs without errors.
TASK 5. Methods Overloading. Review Methods, Implement the following code, test it with different input, make sure it runs without errors.
Solution:
Java code:
Main.java
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Prompt the user to enter number of Integer
System.out.println("Enter the number of integers you will provide: ");
int num = sc.nextInt();
// Prompt the user to enter first Integer
System.out.println("Enter the value of \'a\' and press Enter: ");
int a = sc.nextInt();
// Prompt the user to enter second Integer
System.out.println("Enter the value of \'b\' and press Enter: ");
int b = sc.nextInt();
if(num >= 3){
// Prompt the user to enter third Integer
System.out.println("Enter the value of \'c\' and press Enter: ");
int c = sc.nextInt();
if(num == 3){
// Display result of three number sum
System.out.printf("Provided Integers: %4d and %4d and %4d, the total is %5d\n",a, b, c ,sum(a, b, c));
}
else if ( num== 4){
System.out.println("Enter the value of \'d\' and press Enter: ");
int d = sc.nextInt();
// Display result for four number sum
System.out.printf("Provided Integers: %4d and %4d and %4d and %4d, the total is %5d\n",a, b, c, d ,sum(a, b, c, d));
}
}
else{
// Display result of 2 number sum
System.out.printf("Provided Integers: %4d and %4d, the total is %5d\n",a, b,sum(a, b));
}
}
//this method return the sum of two number
public static int sum(int num1, int num2){
return num1+num2;
}
//this method returns the sum of three numbers
public static int sum(int num1, int num2, int num3){
return num1+num2+num3;
}
//this method returns the sum of four numbers
public static int sum(int num1, int num2, int num3, int num4){
return num1+num2+num3+num4;
}
}
Step by step
Solved in 5 steps with 5 images