[英]Java.Eclipse gives error on declaring a variable with type outside the method with parameters
以下是我的代码,我正在使用Eclipse IDE。
因此,我创建了两个类,其中一个称为Mainclass
,另一个称为Testclass
。
下面的代码可以正常工作,但是如果我在类型为int或integer的计算方法之外声明整数类型的i
和j
变量,并且仅将变量名写在计算方法的括号内,则会显示错误。我想知道为什么这种情况发生在我的原始代码下方,是我上面描述的更改后的代码,上面显示了荒谬的错误。
[原始代码正常工作]
package calculation;
public class Mainclass {
public static void main(String[] args) {
Testclass obj=new Testclass();
System.out.println(obj.calculate(10,20));
}
}
public class Testclass {
int a;
public int calculate(int i, int j) {
a=i+j;
return a;
}
}
[/原始代码可以正常工作]
[此代码无法正常工作]
package calculation;
public class Mainclass {
public static void main(String[] args) {
Testclass obj=new Testclass();
System.out.println(obj.calculate(10,20));
}
}
public class Testclass {
int a;
int i;
int j;
public int calculate(i,j) {
a=i+j;
return a;
}
}
[/此代码无法正常工作]
为什么我们必须在方法的括号内而不是在括号之外声明变量的类型。
提前致谢。
在Java中声明参数的正确方法是
public int calculate(int i,int j){}
提供传递给方法的参数的数据类型
您也可以这样做
public class Testclass {
int a;
int i;
int j;
public int calculate(int i, int j) {
a=i+j;
return a;
}
}
这样可以编译良好。 但是请记住,传递给i & j
参数(即, calculate
方法中的局部变量)与实例变量i & j
没有关系。
public class Testclass {
int a;
int i;
int j;
public int calculate(i,j) {
a=i+j;
return a;
}
}
在方法参数中,您要声明局部变量,它们与实例变量i和j不同。
这意味着:必须使用类型声明它们。 在这一点上,编译器不知道这些局部i和j是什么,因此他不知道如何处理它们。
public class Testclass {
int a;
int i;
int j;
public int calculate(int i, int j) {
a=i+j;
return a;
}
}
这将解决您的问题,但请记住:方法中使用的i和j是局部变量,而不是实例成员。
这是Java编程的要求,在定义方法时,您需要指定该方法具有的参数类型。 参数对应于该方法所期望的原语或类/接口类型的数据类型。
这称为方法的签名
public int calculate(int i, int j)
因此,每当声明一个方法时,都必须定义该方法作为参数的变量的数据类型。
更新:
当您说已经定义的变量时
class Testclass
{
int a;
int i; //this is an instance variable
int j; //this is an instance variable
public int calculate(i, j) // you have to define the type here, method signature does not know what your instance variables are
{
a = i + j;
return a;
}
}
您的代码中存在一些问题:
calculate
。 将参数传递给方法时,需要指定其类型。 Java要求所有变量都具有声明的类型。 MainClass
的实例。 如果要在同一个文件( MainClass.java
)中声明这两个类:
package calculation;
public class Mainclass {
public static class TestClass {
int a;
public int calculate(int i, int j) {
a = i + j;
return a;
}
}
public static void main(String[] args) {
TestClass obj = new TestClass();
System.out.println(obj.calculate(10, 20));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.