[英]Compile error - can somebody please correct me?
I just created a code which represents the sum of integer values from 1 to 10. 我刚刚创建了一个代码,它表示1到10之间的整数值之和。
public class ArithmeticProgress {
public static void main(String args[]) {
int i = 10;
int n;
System.out.println(arithmeticprogress(n, i));
}
static int arithmeticprogress(int n, int i) {
int result = n;
for (n = 0; n < i; n++)
result += result;
return result;
}
}
Unfortunately, it does not compile and therefore it only shows error. 不幸的是,它无法编译,因此仅显示错误。 Can somebody tell me how to correct this code?
有人可以告诉我如何更正此代码吗? Thank you!
谢谢!
You need to initialize n
here. 您需要在此处初始化
n
。
int n=10; // initialize n to some value
System.out.println(arithmeticprogress(n, i)); //else you will get error here
Use IDE
to coding. 使用
IDE
进行编码。 Then you will get 然后你会得到
int n;
System.out.println(arithmeticprogress(n, i));//'n' might not be initialize
Or else you can use n as class level variable. 否则,您可以将n用作类级别变量。 Then it will set to it's default value.
然后将其设置为默认值。
As int n;
作为
int n;
declare in method main, it won't be initialized as it is a local variable and local variable are not initialized automatically. 在方法main中声明,因为它是一个局部变量,并且不会自动初始化,所以不会被初始化。 You need to initialize it explicitly before use.
您需要在使用前显式初始化它。 So changing it to
int n=0;
因此将其更改为
int n=0;
will work. 将工作。
You are getting compilation error because in java local variables are stack variables and they must be initialized before they can be used. 您会收到编译错误,因为在Java中,局部变量是堆栈变量,必须先对其进行初始化,然后才能使用它们。 In your case variable n is used before it is initialized.
在您的情况下,在初始化变量之前先使用它。 Initialized it like this and it should work.
这样初始化它,它应该可以工作。
int n= 1;
There are two problem in your code. 您的代码中有两个问题。
1. You must need to initialize local variable before to use it. 1.必须先初始化局部变量,然后才能使用它。 You need to initialize
n
to 0
or any other value
which is applicable for your logic. 您需要将
n
初始化为0
或any other value
适用于您的逻辑的值。
2. If you want to get the sum of integer from 1 to 10 than your logic is incorrect that's why you got 1024 as a result ( If you initialize n=1 ). 2.如果要获取1到10之间的整数之和,而不是逻辑不正确,这就是为什么结果为1024的原因(如果初始化n = 1)。 you are adding your current result to previous result which is incorrect.
您正在将当前结果添加到错误的先前结果中。 To simply add integer from 1 to 10 i think you didn't need variable
n
in you code. 简单地将1到10之间的整数相加,我认为您在代码中不需要变量
n
。
For this your method should be as shown below : 为此,您的方法应如下所示:
static int arithmeticprogress(int i) {
int result = 0;
for (int n = 1; n <=i; n++)
result = result + n;
return result;
}
It will gives you result as 55
which is summation of 1 to 10 integer number. 它将得到
55
结果,它是1到10整数的和。
May this will help you. 愿这对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.