Click here to Skip to main content
16,004,602 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Write overloaded sumNumber method, one of which takes a single 3-digit integer, the second which takes two 3-digit integers. These methods should return the sum of the individual numbers. For instance if the method is given a value like:

123

The method should return 6 because 1 + 2 + 3 = 6.

My two three digit numbers work and add up just fine but it keeps coming out as 9 and not a different value.

What I have tried:

Java
package methodoverloading;
/**
 *
 * @author stephenwessels
 */
import java.util.Scanner;
public class MethodOverloading 
{
static int i;
static int j;

public static int GetSum(int a)
{
         i = 234;
         j = 0;
        while (i != 0) 
        {
            j += i % 10;
            i /= 10;
        }
        return i + j;
}

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter two three-digit numbers");
        i = in.nextInt();
        j = in.nextInt();
        System.out.println("The sum of the digits is " + GetSum(i));
    }
    
}
Posted
Updated 8-Feb-18 17:46pm
v2
Comments
Richard Deeming 9-Feb-18 10:11am    
Your code doesn't match the description of your homework assignment. You need two methods with the same name, taking a different number of parameters.

Defining Methods (The Java™ Tutorials > Learning the Java Language > Classes and Objects)[^]

1 solution

You are always processing 234 in GetSum. The value you pass in as a should be used instead.
The quick fix is to replace
Java
i = 234;
with
Java
i = a;
 
Share this answer
 
v2
Comments
Barais_19 8-Feb-18 21:49pm    
ok thats all fixed. Now I'm just missing the "make 1+2+3 = 6" method. Any tips on that one?
PIEBALDconsult 9-Feb-18 8:32am    
Isn't that the one above?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900