方法重载问题 [英] Method overloading issue
本文介绍了方法重载问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
写入重载的sumNumber方法,其中一个采用一个3位整数,第二个采用两个3位整数。这些方法应返回各个数字的总和。例如,如果给出的方法值如下:
123
方法应返回6因为1 + 2 + 3 = 6.
我的两个三位数字可以正常工作并加起来很好,但它一直是9,而不是一个不同的值。 />
我尝试过:
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:
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));
}
}
推荐答案
您始终在处理234
inGetSum
。您应该使用以a
传递的值。
快速解决方法是更换
You are always processing234
inGetSum
. The value you pass in asa
should be used instead.
The quick fix is to replace
i = 234;
with
with
i = a;
这篇关于方法重载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文