英文:
Java variable scope in and outside loop
问题
以下是翻译好的部分:
我最近在一个在线Java测试中编写了这段代码。它位于一个被设置为返回整数的方法内部。我收到了一个类似于“变量a没有被赋值”的错误消息。我觉得这很奇怪,因为for循环必须能够访问方法的变量,并且循环内的赋值必须被注册,对吗?
int a;
for(int i=1; i<5; i++){
a = i;
}
return a;
我原本以为这个方法会返回整数5。
这只是关于变量a作用域的问题。我知道这段代码没有意义。
英文:
I wrote this code in an online java test recently. It was inside a method that was set to return an integer. I got an error message something like "variable a has no value assigned to it". I find this odd because the forloop must have access to the methods variable and the assignments inside of the loop must be registered right?
int a;
for(int i=1;i<5;i++){
a = i;}
return a;
I did assume that the method would return the integer 5.
This is only a question regarding scope of the variable a. I know that the code makes no sense.
答案1
得分: 0
你可以尝试下面的代码,这将对你有所帮助。对于任何变量要返回或保存任何值,初始化是必需的。
class a{
public static void main(String[] args) {
System.out.println(test());
}
public static int test(){
int a = 0;
for(int i=1;i<5;i++){
a = i;}
return a;
}
}
英文:
You can try below code , that will help you. Initialisation is mandatory for any variable to return or hold any value.
class a{
public static void main(String[] args) {
System.out.println(test());
}
public static int test(){
int a = 0;
for(int i=1;i<5;i++){
a = i;}
return a;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论